【发布时间】:2021-09-16 06:28:46
【问题描述】:
我有一个类,它基本上是 PHP 的 DirectoryIterator 的装饰器。每个文件的内容由类处理,然后由current() 方法返回。目前,当文件是点文件或文件无法处理时,我从current()方法返回false。但我宁愿跳过点和不可处理的文件,只返回处理过的数据。
附:下面的代码是一个简化的示例。我不想在构造函数中预处理所有文件。
class Pages implements \Iterator
{
public function __construct(string $path)
{
$this->di = new \DirectoryIterator($path);
}
public function rewind() {
return $this->di->rewind();
}
public function current() {
$file = $this->di->current();
if($file->isDot()) {
return false;
}
$content = file_get_contents($file->getPathName());
if($content === 'Cannot be processed!') {
return false;
}
return $content;
}
public function key() {
return $this->di->key();
}
public function next() {
return $this->di->next();
}
public function valid() {
return $this->di->valid();
}
}
【问题讨论】:
-
我认为在您的
current中,您可以针对现有的false条件重复调用$this->di->current()。实际上,您最终会得到一个while循环或类似的循环。 -
@Chris Haas - 感谢您的建议。我发布了我的问题的答案。
标签: php design-patterns iterator decorator