这个答案主要是基于你目前的解决方案,用一些原始问题。
与使用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,
],
];
// ...
}
现在我们只需要提出事件 - 请参阅我的另一篇关于Model Observers的文章。首先,您需要导入Event
和App\Events\UserHasRegistered
,然后在您的created
方法中,请拨打Event::fire(new UserHasRegistered($user))
。
你就不能在此设置了'__construct'的'Model'的? –
我不确定它没有被添加到用户表中,它使用用户的ID来创建外键 –
您是否想根据他们选择的内容来分配不同的角色?总是被赋予一定的作用? – Joe