virtualcomplete / selector
选择器模式抽象类,用于在用户层面或运行时处理多态。
dev-master
2017-01-15 22:02 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: ~4.0
This package is not auto-updated.
Last update: 2024-09-23 15:36:00 UTC
README
选择器
这是一个抽象类,允许您轻松实现提供的选择器模式。
要求:PHP >5.4.0
选择器模式是什么?
这个选择器模式提供了一种简单的方法来处理用户层面或运行时级别的多态。这意味着什么?好吧,如果您针对接口进行编码,您应该已经熟悉多态性。它允许您使用相同的接口插入不同的服务。许多框架通过在应用程序级别绑定的方式处理这些服务的依赖注入。但是,如果您有多个基于用户设置可能适用的服务怎么办?这正是这个模式发挥作用的地方。请参见下面的支付方式示例。
用法
只需扩展选择器类,并按文档填写抽象方法。getKey()应根据应用程序传递给它的参数返回setMappings()数组中的其中一个键。
示例
class PaymentMethodSelector extends Selector { protected function setInterface() { return 'VirtualComplete\Selector\Example\PaymentMethodInterface'; // Easier on PHP >= 5.5 // return PaymentMethodInterface::class; } protected function setMappings() { return [ 'cash' => 'VirtualComplete\Selector\Example\CashPaymentMethod', 'check' => 'VirtualComplete\Selector\Example\CheckPaymentMethod', 'credit' => 'VirtualComplete\Selector\Example\CreditPaymentMethod' ]; } public function getKey($arguments) { $user = $arguments[0]; return $user['paymentMethod']; } protected function defaultKey() { return 'cash'; } }
然后通过传递您的$user数据检索其中一个类。
$user['paymentMethod'] = 'credit'; $method = $selector->selectFrom($user); // Returns CreditPaymentMethod instance
使用依赖注入和您的选择器以获得最佳效果。