linkorb / bus
命令总线组件
dev-master
2015-01-18 14:37 UTC
Requires (Dev)
- phpunit/phpunit: ~4.4
- symfony/console: ~2.4
This package is auto-updated.
Last update: 2024-08-29 03:29:31 UTC
README
此独立组件实现了命令模式。
它受到Laravel的illuminate/bus
和illuminate/queue
组件的启发,但旨在框架无关。
有关命令总线模式的更多信息
使用方法
任何Command
都需要两个类:DoSomethingCommand
类和DoSomethingHandler
类。
您可以在需要时从控制器中实例化命令,并将其dispatch
到总线。
然后总线将解析匹配的处理器类,并要求它处理新的命令。
以下是您如何使用它的示例
一个示例命令类
<?php use LinkORB\Component\Bus\CommandInterface; class OrderConfirmCommand implements CommandInterface { private $orderId; public function __construct($orderId) { $this->orderId = $orderId; } public function getOrderId() { return $this->orderId; } }
一个示例处理器类
<?php use LinkORB\Component\Bus\HandlerInterface; use LinkORB\Component\Bus\CommandInterface; class OrderConfirmHandler implements HandlerInterface { private $db; private $mailer; // the constructor automatically receives requested services from the container public function __construct($db, $mailer) { $this->db = $db; $this->mailer = $mailer; } // this method is called by the bus to handle commands public function handle(CommandInterface $command) { $order = $this->db->fetchOneById('orders', $command->getOrderId()); $this->mailer->mail($order['email'], "Thanks for your order, " . $order['customername']); } }
在您的初始化脚本中设置总线
use LinkORB\Component\Bus\Bus; // Reuse an existing container, or create a plain php array // Any array type dependency injection container will work too (symfony, pimple, etc) $container = array( 'db'=>$db, 'mailer'=>$mailer ); // Instantiate the bus, and optionally pass a container $bus = new Bus($container); // now add the bus to the container, or use any other method to pass the bus to your controllers
在您的控制器中使用总线
class basketController
{
public function confirmAction()
{
$orderid = 5;
// Instantiate a Command
$command = new OrderConfirmCommand($orderid);
// Dispatch the command
$this->bus->dispatch($command);
}
}
从命令行调用命令
包括一个简单的命令行分发器。它可以这样使用
./vendor/bin/bus bus:dispatch "Acme\Bus\DoSomethingCommand" -p color="red" -g os="linux"
-p
参数将被作为参数传递给命令。您可以传递任意多个。 -g
参数将被插入到简单的数组“容器”中,因此它可以通过处理器使用
包括了一个示例命令
./vendor/bin/bus bus:dispatch "LinkORB\Component\Bus\Bus\HelloCommand" -p name="World" -g sender="me"
这将输出
Hello, World from me!
许可证
MIT(见LICENSE.md)
由LinkORB工程团队提供
在我们的linkorb.com/engineering上查看我们的其他项目。
顺便说一句,我们正在招聘!