pushoperations / decorators
此包已被废弃且不再维护。未建议替代包。
装饰器库。
v1.0.0
2015-06-19 23:12 UTC
Requires
- php: >=5.4.0
- illuminate/support: 4.2.*|5.0.*|5.1.*
Requires (Dev)
- phpunit/phpunit: 4.3.*
- sami/sami: 2.0.*
- satooshi/php-coveralls: dev-master
This package is not auto-updated.
Last update: 2024-09-14 17:00:49 UTC
README
一个用于装饰数组(特别是Laravel的Input::)的库,以便进行操作并将数据作为服务返回以用于构建对象。
注意:此库未来可能包含其他模式。
内容
安装
推荐通过Composer进行安装。
更新您的项目composer.json文件以包含Decorators
{ "require": { "pushoperations/decorators": "1.*" } }
然后更新项目依赖关系以包含此库
composer update pushoperations/decorators
安装后,您需要引入Composer的自动加载器
require 'vendor/autoload.php';
使用方法
通过以下方式创建您自己的装饰器:
- 从
DataDecorator
抽象类扩展 - 创建一个接受数组的构造函数
- 可选:添加特定于生成所需数据数组的特定方法
一个用例是将输入数据拆分为不同的数组,以便不同的工厂用于构建新对象。
一个方便的效果是您可以在返回数据数组之前在装饰器方法内执行清理。
示例
use Push\Decorators\DataDecorator; use Push\Decorators\DataDecoratorInterface; class BasicDecorator extends DataDecorator implements DataDecoratorInterface { public function __construct(array $input) { $this->data = $input; } } class ComplexDecorator extends DataDecorator implements DataDecoratorInterface { public function __construct(array $input) { $this->data = $input; } public function complicate() { return array_map($this->data, function($value) { if (is_int($value)) { return $value * 2; } }); } }
常见的用法是对创建/更新过程中的用户输入进行过滤和拆分。
$input = [ 'name' => 'Push Operations', 'desks' => 50, 'employees' => [ 'John', 'Jane', ], ]; $basic = new BasicDecorator($input); // Check if value for key exists echo $basic->has('desks'); // true echo $basic->has('chairs'); // false // Provide a default value if it doesn't exist echo $basic->get('name'); // 'Push Operations' echo $basic->get('chairs', 10); // 10 // Get some of the data var_dump($basic->only('name', 'desks')); // ['name' => 'Push Operations', 'desks' => 50] var_dump($basic->only(['name', 'desks'])); // ['name' => 'Push Operations', 'desks' => 50] var_dump($basic->except('name')); // ['desks' => 50, 'employees' => ['John', 'Jane']] // Get all of the data var_dump($basic->all()); // The $input array // Add data $add = [ 'interns' => [ 'Billy', 'Derrick' ], ]; $basic->merge($add); var_dump($basic->get('interns')); // ['Billy', 'Derrick'] // You can redecorate the results of the decorator (with itself or another decorator) to do more manipulation. $complex = new ComplexDecorator($basic->all()); var_dump($complex->complicate()); // [..., 'desks' => 100, ...];