2016-09-22 9 views
2

저는 Laravel 5.3과 협력 중이며 다른 사람이 가입 할 때 역할을 설정하려고하는데 Zizaco Entrust 라이브러리를 사용했습니다.Laravel 5.3 - 가입시 Entrust 역할을 구현하는 가장 좋은 방법은 무엇입니까?

나는 이와 같은 것을 달성하기위한 최선의 방법에 확신이 없습니다.

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); 
} 

을하지만, 분명히 그것은 옳지 않아 :

나는이 내부 RegisterControllercreate 방법을 아래와 같이 할 것을 시도했다. 그래서 나는 이런 종류의 일로 최고의 실천이 무엇인지 확신 할 수 없다.

+0

방금이 설정할 수없는'은'Model'의 __construct'? –

+0

'Users' 테이블에 추가되지 않았기 때문에 사용자의 ID를 사용하여 외래 키를 생성합니다. –

+0

사용자가 선택한 항목에 따라 다른 역할을 할당하겠습니까? 항상 특정 역할을 부여 받습니까? – Joe

답변

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); 
     // ... 
    } 

    // ... 

} 
+0

이것은 완벽하게 작동했습니다. 고맙습니다! –

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

그것은 최고의 솔루션이 아닐 수도 있지만이하는직업, 미래의 교수이기 때문에 사용자 생성에 대한 논리가 커지면 구현할 수 있습니다.

+0

이것은 'RegisterController.php'를 수정합니까? –

+0

첫 번째 비트는 사용자 모델에 있습니다. 그것을 만들기위한 호출은 컨트롤러에 있습니다. 그것이 의미가되기를 바란다 –

+0

Gotcha, 그래서 당신은 창조 방법을 가져 가고 모델 안에서 그것을 수정하고있다, 나는 이해한다 –

1

이 답변은 주로 현재의 해결책을보고 원래 질문의 대시로 표시됩니다.

createNew과 같은 방법으로 모델을 작성하는 대신, 모델과 상호 작용하기 위해 특별히 유형의 클래스를 만드는 경우 관리하기가 더 쉽습니다. 이것을 리포지토리 또는 서비스 또는 무엇이든지 좋아하는 것으로 부를 수는 있지만 서비스로 실행합니다. 깨끗하게 해결 될 수있다 -

// app/Models/User.php 
class User ... { 

    public function setPasswordAttribute($password) { 
     $this->attributes[ 'password' ] = bcrypt($password); 
    } 

} 

그리고 지금 우리가 활성화 이메일을 전송하는 문제가있다 :

// 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; 
    } 

} 

이제 우리는 우리가 암호 해시를 잃었다는 사실 다룰 필요 이벤트.

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에게 방금 만든 이벤트와 수신기가 관련이 있다는 것을 말한 다음 이벤트를 발생시키는 것입니다.

// 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, 
     ], 
    ]; 

    // ... 

} 

이제 이벤트를 제기하면됩니다. 모델 관찰자에 관한 다른 게시물을 참조하십시오. 먼저 EventApp\Events\UserHasRegistered을 가져오고 created 방법에서는 Event::fire(new UserHasRegistered($user))을 호출하면됩니다.

+0

좋은 대답. 내가 직장에서 집에 돌아 왔을 때 나는 이것을 줄 것이다. 아주 좋아 보인다. –

+1

@AndyHolmes 방금 Laravel에는 여러 가지 방법으로 작업하고 있습니다. 역할이 알려져 있다면, 암호 속성에 뮤 테이터를 사용하고 어쨌든 이메일에 이벤트/리스너 설정을 사용하는 것이 좋지만 다른 방법이 더 좋습니다. 모델에서 좀 더 복잡한 작업을 수행해야하는 경우 서비스도 그에 대한 좋은 방법입니다 – Joe

+0

감사합니다. Joe, 진심으로 감사합니다. –