graze / formatter
通过应用处理器、过滤器排序器,将对象转换为数据数组。
v0.2.0
2016-04-07 08:58 UTC
Requires
- php: ^5.5 || ^5.6 || ^7.0
- graze/sort: ^2.0.1
Requires (Dev)
- graze/hamcrest-test-listener: ^1.0
- hamcrest/hamcrest-php: ^1.2
- phpunit/phpunit: ^4.8 || ^5.0
This package is auto-updated.
Last update: 2024-08-29 03:23:56 UTC
README
在我们的博客文章中了解更多关于我们为什么制作这个库的原因。
安装
我们建议使用Composer安装此库。
~$ composer require graze/formatter
使用方法
// Create a formatter ... class CountableFormatter extends \Graze\Formatter\AbstractFormatter { protected function convert($object) { if (! $object instanceof Countable) { throw new \InvalidArgumentException(sprintf('`$object` must be an instance of %s.', Countable::class)); } return [ 'count' => $object->count(), ]; } } // ... processor ... $processor = function (array $data, Countable $object) { // Let's add the square of count. $data['square'] = $data['count'] ** 2; return $data; }; // ... filter ... $filter = function (array $data) { // Remove elements with a square of 9. return $data['square'] !== 9; }; // ... sorter ... $sorter = function (array $data) { // Sort by count in descending order. return $data['count'] * -1; }; // ... and something we can format. class ExampleCountable implements Countable { private $count = 0; public function count() { return $this->count += 1; } } $countable = new ExampleCountable(); // Create a new instance of the formatter, and register all the callables. $formatter = new CountableFormatter(); $formatter->addProcessor($processor); $formatter->addFilter($filter); $formatter->addSorter($sorter); // Format a single object. $result = $formatter->format($countable); print_r($result); // Format several objects. $result = $formatter->formatMany([$countable, $countable, $countable]); print_r($result);
上面的示例将输出
Array
(
[count] => 1
[square] => 1
)
Array
(
[0] => Array
(
[count] => 4
[square] => 16
)
[1] => Array
(
[count] => 2
[square] => 4
)
)
更多文档可以在docs/
下找到。