So after watching the following video about 8 times things started to click in my head. Now I'm somewhat understanding how the purpose of commands and how to deal with them either self handling or whether there's a handler class for performing this task. I still have a couple of questions though before I dive into trying to wrap my head around Events.
https://laracasts.com/lessons/laravel-5-commands
Questions
- From the way I've coded this. Does it look like I'm getting it or am I still missing something important?
- In the CreateUserCommandHandler with the call to the create method on the user repository inside the handle method is that how I should be sending my data to the repository?
Code
<?php namespace App\Http\Controllers;
use App\Repositories\Users\UserRepository;
use App\Repositories\Roles\RoleRepository;
use App\Commands\CreateUserCommand;
use App\Http\Requests;
use App\Http\Requests\UserRequest;
use Illuminate\HttpResponse;
use App\Http\Controllers\Controller;
class UsersController extends Controller {
private $userRepository;
private $roleRepository;
/**
* @param UserRepository $userRepository
* @param RoleRepository $roleRepository
*/
public function __construct(UserRepository $userRepository, RoleRepository $roleRepository)
{
$this->userRepository = $userRepository;
$this->roleRepository = $roleRepository;
}
/**
* Save a new user.
*
* @param UserRequest $request
*
* @return Response
*/
public function store(UserRequest $request)
{
// formally had $this->userRepository->create($request->all());
$this->dispatchFrom(CreateUserCommand::class, $request);
return redirect('users');
}
}
<?php namespace App\Commands;
use App\Commands\Command;
class CreateUserCommand extends Command {
public $first_name;
public $last_name;
public $display_name;
public $email;
public $password;
public $role_id;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct($first_name, $last_name, $display_name, $email, $password, $role_id)
{
$this->first_name = $first_name;
$this->last_name = $last_name;
$this->display_name = $display_name;
$this->email = $email;
$this->password = $password;
$this->role_id = $role_id;
}
}
<?php namespace App\Handlers\Commands;
use App\Commands\CreateUserCommand;
use App\Repositories\Users\UserRepository;
use Illuminate\Queue\InteractsWithQueue;
class CreateUserCommandHandler {
/**
* @var UserRepository
*/
private $userRepository;
/**
* Create the command handler.
*
* @return void
*/
public function __construct(UserRepository $userRepository)
{
//
$this->userRepository = $userRepository;
}
/**
* Handle the command.
*
* @param $command
* @return void
*/
public function handle(CreateUserCommand $command)
{
$this->userRepository->create($command);
}
}