widefocus / feed-writer
此包包含用于编写订阅源模型的代码。
1.0.0
2017-04-27 15:20 UTC
Requires
- php: ^7.0
Requires (Dev)
- phpunit/phpunit: ^6.0
- widefocus/filter: ^1.0
This package is not auto-updated.
Last update: 2024-09-20 22:23:06 UTC
README
此包包含用于编写订阅源模型的代码。
安装
使用composer安装此包。
$ composer require widefocus/feed-writer
用法
此包旨在作为订阅源编写实现的基类。为此,需要实现一个编写器。
编写器
编写器处理订阅源数据。
<?php use WideFocus\Feed\Writer\WriterInterface; use WideFocus\Feed\Writer\WriterFieldInterface; use WideFocus\Feed\Writer\WriterTrait; class DebugWriter implements WriterInterface { use WriterTrait; /** * @var WriterFieldInterface[] */ private $fields; /** * Constructor. * * @param WriterFieldInterface[] $fields */ public function __construct(array $fields) { $this->fields = $fields; } /** * Write an item to the feed. * * @param ArrayAccess $item * * @return void */ protected function writeItem(ArrayAccess $item) { foreach ($this->fields as $field) { echo sprintf( "%s: %s\n", $field->getLabel(), $field->getValue($item) ); } } /** * Initialize the feed. * * @return void */ protected function initialize() { } /** * Finish the feed. * * @return void */ protected function finish() { } }
编写订阅源
编写器期望一个迭代器作为输入。迭代器应包含实现ArrayAccess接口的项目。
<?php use WideFocus\Feed\Writer\WriterField; $items = new ArrayIterator( [ new ArrayObject(['foo' => 'FooValue', 'bar' => 'BarValue']), new ArrayObject(['foo' => 'AnotherFooValue', 'bar' => 'AnotherBarValue']) ] ); $fields = [ new WriterField('foo', 'Foo'), new WriterField('bar', 'Bar', 'strtoupper') ]; $writer = new DebugWriter($fields); $writer->write($items);
这将导致以下输出
Foo: FooValue
Bar: BARVALUE
Foo: AnotherFooValue
Bar: ANOTHERBARVALUE