该答案主要基于查看您当前的解决方案,并带有一些原始问题。
createNew如果您创建一种专门用于与模型交互的类,您可能会发现事情更容易管理,而不是使用类似的方法来填充您的模型。您可以将其称为存储库或服务或任何您喜欢的名称,但我们将使用服务运行。
// app/Services/UserService.php
<?php namespace App\Services;
use App\Models\User; // or wherever your User model is
class UserService {
public function __construct( User $user ) {
$this->user = $user;
}
public function create( array $attributes, $role = null ) {
$user = $this->user->create( $attributes );
if ( $role ) {
$user->attachRole( $role );
}
return $user;
}
}
现在我们需要处理我们丢失了密码散列的事实:
// app/Models/User.php
class User ... {
public function setPasswordAttribute( $password ) {
$this->attributes[ 'password' ] = bcrypt( $password );
}
}
现在我们遇到了发送激活电子邮件的问题——这可以通过事件彻底解决。在终端中运行:
php artisan make:event UserHasRegistered
它应该看起来像这样:
// app/Events/UserHasRegistered.php
<?php namespace App\Events;
use App\Models\User;
use Illuminate\Queue\SerializesModels;
class UserHasRegistered extends Event {
use SerializesModels;
public $user;
public function __construct( User $user ) {
$this->user = $user;
}
}
现在我们需要一个事件监听器:
php artisan make:listener SendUserWelcomeEmail
这可以像你喜欢的那样复杂,这是我只是从我周围的一个项目中复制/粘贴的一个:
// app/Listeners/SendUserWelcomeEmail.php
<?php namespace App\Listeners;
use App\Events\UserHasRegistered;
use App\Services\NotificationService;
class SendUserWelcomeEmail {
protected $notificationService;
public function __construct( NotificationService $notificationService ) {
$this->notify = $notificationService;
}
public function handle( UserHasRegistered $event ) {
$this->notify
->byEmail( $event->user->email, 'Welcome to the site', 'welcome-user' )
->send();
}
}
剩下的就是告诉 Laravel 我们刚刚创建的 Event 和 Listener 是相关的,然后触发该事件。
// app/Providers/EventServiceProvider.php
use App\Events\UserHasRegistered;
use App\Listeners\SendUserWelcomeEmail;
class EventServiceProvider extends ServiceProvider {
// find this array near the top, and add this in
protected $listen = [
UserHasRegistered::class => [
SendUserWelcomeEmail::class,
],
];
// ...
}
现在我们只需要引发事件 - 请参阅我关于模型观察者的另一篇文章。首先,您需要导入Eventand App\Events\UserHasRegistered,然后在您的created方法中,只需调用Event::fire( new UserHasRegistered( $user ) ).