我正在 Laravel 中构建一个 ticketSystem api。我有很多事件。我想知道我是否做对了。因此,例如,当创建用户时,它会触发事件:CreateUserEvent
该事件有几个听众,例如:
- 创建用户
- 创建包
- 发送邮件
我几乎为每件脏东西准备了一个有多个听众的事件。这是做这种事情的正常方式吗?在我的 Controller 中,我几乎只触发事件。
我已经看过一些关于事件的视频,例如 ( https://laracasts.com/series/intermediate-laravel/episodes/3 ) 但我还是有点困惑。
所以基本上我的问题是:您的 webapp 存在于很多事件之外是否正常?如果不是,您在哪里使用事件?
最佳答案
实际上,您正在使它变得复杂。对单个事件使用单个事件监听器,并在该事件处理程序中执行操作。例如:
伪代码
// In EventServiceProvider
protected $listen = [
'user.created' => ['App\Handlers\Events\UserEvents@userCreated'],
],
在您的应用中的某处:
// ...
if($user = User::create($request->all())) {
app('event')->fire('user.created', $user);
}
...
处理程序App\Handlers\Events\UserEvents@userCreated
:
<?php namespace App\Handlers\Events;
use App\User;
use App\Package;
use App\Services\Mail\UserMailer;
class UserEvents {
protected $mailer = null;
protected $package = null;
public function __construct(UserMailer $mailer, Package $package)
{
$this->mailer = $mailer;
$this->package = $package;
}
public function userCreated(User $user)
{
$this->package->create($user); // <-- An action to be taken
$this->mailer->notifyUser($user); // <-- Another action to be taken
}
}
因此,通过这种方式,您可以处理事件并使用处理程序针对特定事件为您执行其他操作。
关于php - Laravel 很多事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36332615/