這個答案主要是基於你目前的解決方案,用一些原始問題。
與使用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