赵伟明/yii-tactician

Yii 对 league/tactician 命令总线模式的适配实现

0.1.1 2015-09-21 08:54 UTC

This package is not auto-updated.

Last update: 2024-10-02 10:01:56 UTC


README

#Yii-Tactician Yii-Tactician 是 Yii 对 Tactician 命令总线库 的适配器。它为在基于 Yii 的应用程序中使用命令总线模式提供了一种简单的方法。

##安装 您可以通过运行 composer require pavelmics/yii-tactician 或者在您的 composer.json 文件中添加 "pavelmics/yii-tactician": "0.1.1" 来安装 Yii-Tactician。

##配置 一旦安装了库,请按以下方式修改您的应用程序配置

return [
	...
	'components' => [
    	...
		'commandBus' => [
    		'class' => 'YiiTactician\YiiTacticianCommandBus',
        ],
    ],
    ...
];

默认情况下,Yii Tactician 使用 bus_commands 目录来存储命令处理程序,您可以通过配置 handlersPath 并使用以下数组形式的 yii-aliases 来更改此设置

return [
	...
	'components' => [
    	...
		'commandBus' => [
    		'class' => 'YiiTactician\YiiTacticianCommandBus',
            'handlersPath' => [
            	'application.command_bus.handlers',
                'appliction.modules.command_bus',
            ],
        ],
    ],
    ...
];

注意:不要使用 * 别名,您的别名必须指向一个目录,而不是一个文件!注意2:同时,您必须使用 psr-4 自动加载系统来使用 Yii-Tactician(只需在您的 index.php 和 console.php 中添加 require('path/to/vendor/autoload.php'); 即可)。

##使用

###基本 在您的应用程序的某个位置定义一个命令类,例如

class TestCommand 
{
	public $someParam;
    public $someOtherParam;
    
    public function __construct($someParam, $someOtherParam = 'defaultValue') 
    {
    	$this->someParam = $someParam;
        $this->someOtherParam = $someOtherParam;
    }
}

然后,在您的处理程序路径之一(见此说明书的配置部分)下定义一个处理程序类。处理程序类的名称必须是命令类名称,后缀为 "Handler"。例如,对于类 TestCommand,我们需要定义 TestCommandHandler

class TestCommandHandler
{
	public function handle(TestCommand $command)
    {
    	// do command stuff hire!
        // we can use $command->someParam and $this->someOtherParam
    }
}

现在我们可以在控制器(或您想要的地方)中使用这个命令

...
public function actionCreateSomething()
{
	$someParam = Yii::app()->request->getPost('some_param');
	$command = new TestCommand($someParam);
    $result = Yii::app()->commandBus->handle($command);
    if ($result) {
    	$this->redirect(
        	Yii::app()->createUrl('something/show', ['id' => $result->id])
        );
    } else {
    	$this->render('errorSomething');
    }
}

###基于控制器的处理程序 有时候我们需要以几种不同的方式处理一个命令。假设我们需要注册用户。有时用户通过电子邮件注册,有时通过电话号码注册。我们需要处理注册命令几乎相同,但同时略有不同。为了实现这一点,我们可以在处理程序类中定义几个处理函数(就像标准的 Yii 控制器一样)。例如

class RegisterCommandHandler
{
	public function byPhone($command)
    {/* code to register by phone */}
    
    public function byEmail($command)
    {/* code to register by email */}
}

然后使用 YiiTactician\ControllerBaseCommand 来定义您的命令类

class RegisterCommand extends YiiTactician\ControllerBaseCommand 
{}

现在您可以这样做

$params = ['email' => 'test@test.com', 'password' => 'pass'];
$command = new RegisterCommand($params, 'byEmail');
\Yii::app()->commandBus->handle($command);

// or
$params = ['phone' => '99-99-99-99'];
$command = new RegisterCommand($params);
$command->setHandlerMethod('byPhone');
\Yii::app()->commandBus->handle($command);