jeroen / batching-iterator
批量获取值的迭代器
3.0.0
2017-05-16 00:44 UTC
Requires
- php: >=7.0
Requires (Dev)
- mediawiki/mediawiki-codesniffer: ~0.6.0
- ockcyp/covers-validator: ~0.6
- phpunit/phpunit: ~6.0
- squizlabs/php_codesniffer: ~2.5
Replaces
README
这是一个小型库,提供了一种 Iterator
,它可以批量请求额外的值。这对于迭代器访问成本较高的数据很有用,例如数据库或Web API。
类概述
核心接口
BatchingIterator
- 通过BatchingFetcher
批量请求的迭代器BatchingFetcher
- 具有带有fetchNext
方法的接口。您可能需要创建一个实现
实用工具
MultipleBatchingFetcher
- 将多个BatchingFetcher
实例组合成一个InMemoryBatchingFetcher
- 将一个array
转换为BatchingFetcher
接口IteratorBasedBatchingFetcher
- 将一个Iterator
转换为BatchingFetcher
接口
用法
创建一个使用 Iterator
的服务。
class TweetImporter { public function importTweets( Iterator $tweets ) { foreach ( $tweets as $tweet ) { $this->tweetStore->saveTweet( $tweet ); } } }
注意该服务仅依赖于 Iterator。它不知道 Iterator 如何提供其结果。因此,您将服务从检索结果的主体中解耦,并从何时开始。这些值可能已经存在于内存中,封装在 ArrayIterator
中,或者随着迭代的发生从 Web 服务中获取。使用 ArrayIterator
对于测试非常有帮助。
实现 BatchingFetcher
接口。如果您已经有了检索数据的服务,这可以是一个简单的包装器。
class BatchingTweetFetcher implements BatchingFetcher { public function fetchNext( $maxFetchCount ) { // Make a call to some external service to fetch $tweets return $tweets; } public function rewind() { // Go back to the first tweet } }
现在您可以轻松地实例化服务,获得批量优化,并使所有职责很好地解耦。
class TweetImportCli { public function importTweets() { $tweetIterator = new BatchingIterator( new BatchingTweetFetcher() ); $tweetIterator->setMaxBatchSize( 42 ); $this->tweetImporter->importTweets( $tweetIterator ); } }
安装
您可以使用 Composer 下载并安装此包以及其依赖项。
要将此包作为本地、针对项目的依赖项添加到您的项目中,只需将 jeroen/batching-iterator
添加到项目中的 composer.json
文件中的依赖项即可。以下是一个定义对 BatchingIterator 3.x 依赖项的 composer.json
文件的示例。
{ "require": { "jeroen/batching-iterator": "~3.0" } }
发行说明
版本 3.0.0 (2017-05-16)
- 弃用了对 PHP 5.x 的支持
- 添加了标量和返回类型提示
版本 2.1.2 (2014-11-02)
BatchingIterator
中的最大批量大小现在默认为 10,避免了在没有设置此值的情况下使用迭代器。
版本 2.1.1 (2014-08-19)
- 以包名
jeroen/batching-iterator
代替jeroen-de-dauw/batching-iterator
发布。
版本 2.1 (2014-07-19)
MultipleBatchingFetcher
现在接受一个包含BatchingFetcher
的数组作为其构造函数参数
版本 2.0 (2014-07-19)
重大更改
- 向
BatchingFetcher
接口添加了rewind
方法 - 将
BatchingIterator\InMemoryBatchingFetcher
重命名为BatchingIterator\Fetchers\InMemoryBatchingFetcher
新功能和改进
BatchingIterator
现在可以多次迭代- 添加了
MultipleBatchingFetcher
- 添加了
IteratorBasedBatchingFetcher
版本 1.0 (2014-07-03)
初始版本包含以下内容:
BatchingIterator
类BatchingFetcher
接口InMemoryBatchingFetcher
是BatchingFetcher
的简单实现