minhlhst/command-bus

ST团队为Laravel框架提供的简单命令总线

1.0.0 2023-10-30 17:37 UTC

This package is auto-updated.

Last update: 2024-10-01 00:20:42 UTC


README

ST团队为Laravel框架提供的简单命令总线

安装

composer require minhlhst/command-bus

如果你的Laravel版本低于5.5,请将以下行添加到 config / app.php 文件中的 providers 数组中:

MinhlhSt\CommandBus\CommandBusServiceProvider::class,

示例

class UserController extends Controller
{
    public function store(Request $request)
    {
        $user = $this->dispatch(new RegisterUserCommand(
            $request->input('email'),
            $request->input('password')
        ));
    
        return $user;
    }
}

用法

命令

use MinhlhSt\CommandBus\Command;

class RegisterUserCommand implements Command
{
     public function __construct(
        private string $name,
        private string $password
    )
    {
    }
    
    public function email(): string
    {
        return $this->email;
    }
    
    public function password(): string
    {
        return $this->password;
    }
    
    public function setName(string $name): void
    {
        $this->name = $name;
    }

    public function setPassword(string $password): void
    {
        $this->password = $password;
    }
}

处理器

use MinhlhSt\CommandBus\Handler;
use MinhlhSt\CommandBus\Command;

class RegisterUserHandler implements Handler
{
    private $userRepository;
    
    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }
    
    public function handle(Command $command): User
    {
        $user = new User(
            $command->email(),
            $command->password()
        );
        
        $this->userRepository->store($user);
        
        return $user;
    }
}

控制器

use MinhlhSt\CommandBus\AbsctractController;
use MinhlhSt\CommandBus\CommandBus;
use MinhlhSt\CommandBus\Command;

class Controller extends AbsctractController
{
    private $dispatcher;
    
    public function __construct(CommandBus $dispatcher) 
    {
        $this->dispatcher = $dispatcher;
    }
    
    public function dispatch(Command $command)
    {
        return $this->dispatcher->execute($command);
    }
}
class UserController extends Controller
{
    public function store(Request $request)
    {
        $user = $this->dispatch(new RegisterUserCommand(
            $request->input('email'),
            $request->input('password')
        ));
    
        return $user;
    }
}