2

我正在与我一起工作,Laravel 5.3并且我正在尝试在有人注册时设置一个角色,我已经使用了该Zizaco Entrust库。

我不确定实现此类目标的最佳方法。

我尝试在RegisterController'screate方法中执行此操作,如下所示:

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

    $user = User::where('email', '=', $data['email'])->first();

    // role attach alias
    $user->attachRole($employee);
}

但显然这是不对的。所以我有点不确定这种事情的最佳实践是什么。

4

3 回答 3

2

如果正如您对 OP 的评论所建议的那样,您总是想为注册用户分配相同的角色,您可以为此使用模型观察者 - 这真的很简单。

// app/Observers/UserObserver.php

<?php namespace App\Observers;

use App\Models\User;
use App\Models\Role; // or the namespace to the Zizaco Role class

class UserObserver {

    public function created( User $user ) {
        $role = Role::find( 1 ); // or any other way of getting a role
        $user->attachRole( $role );
}

然后,您只需在 AppServiceProvider 中注册观察者:

// app/Providers/AppServiceProvider.php

use App\Models\User;
use App\Observers\UserObserver;

class AppServiceProvider extends Provider {

    public function boot() {
        User::observe( new UserObserver );
        // ...
    }

    // ...

}
于 2016-09-22T15:53:06.837 回答
1

该答案主要基于查看您当前的解决方案,并带有一些原始问题。

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 ) ).

于 2016-09-22T15:49:04.303 回答
0

我最终做了什么,因为我确实需要做的不仅仅是对用户创建的一项操作是为用户创建提供另一个功能。

用户模型

/**
 * Create a new user instance after a valid registration.
 *
 * @param array $attributes
 * @param null  $role
 * @param bool  $send_activation_email
 *
 * @return User $user
 *
 * @internal param array $args
 */
public function createNew(array $attributes, $role = null, $send_activation_email = true)
{
    $this->name = $attributes['name'];
    $this->company_id = $attributes['company_id'];
    $this->email = $attributes['email'];
    $this->password = bcrypt($attributes['password']);
    $this->save();

    if (isset($role)) {
        // Assigning the role to the new user
        $this->attachRole($role);
    }

    //If the activation email flag is ok, we send the email
    if ($send_activation_email) {
        $this->sendAccountActivationEmail();
    }

    return $this;
}

并称它为:

用户控制器

$user = new User();
$user->createNew($request->all(), $request->role);

它可能不是最好的解决方案,但它可以完成工作,而且它是未来的教授,所以如果用户创建的逻辑增长也可以实现。

于 2016-09-22T15:07:32.333 回答