Iterators Magic
Iterators magic is a way to iterate everything (folder - files - pdo vs.) with OOP structure., (*1)
Gives you, the separation of concerns and extendable class structure while you have an iterator with a renderer class., (*2)
Please don't hesitate to contribute if you have different opinion that you want to share., (*3)
Usage
You can use any renderer class to render result of the Iteration class ( SPL class ), (*4)
There is an example in project that called HtmlDirectoryRenderer to print the results to a page with html design., (*5)
$data = new HtmlDirectoryRenderer(
new LocalDirectoryIterator('/var/www')
);
$data->render();
Iterator Class use IteratorAggregate interface and getIterator() method for iteration., (*6)
You can change easily DirectoryIterator and Renderer Type., (*7)
For example if you want to iterate a remote directory folder with a ftp connection,, (*8)
You can create a class FtpDirectoryIterator :, (*9)
You can pass configuration with AbstractDirectoryIterator to your main Iterator class., (*10)
$data = new HtmlDirectoryRenderer(
new FtpDirectoryIterator('/var/www',$config)
);
$data->render();
TreeIterator, (*11)
TreeIterator example of view folder structure as tree view., (*12)
$data = new TreeDirectoryRenderer(
new TreeDirectoryIterator('/var/www/playground')
);
$data->render();
//Output
[tree]
├ /var/www/playground/app
├ /var/www/playground/package.json
├ /var/www/playground/gulpfile.js
├ /var/www/playground/.git
├ /var/www/playground/config.js
├ /var/www/playground/.babelrc
├ /var/www/playground/readme.md
├ /var/www/playground/.gitignore
├ /var/www/playground/merger
├ /var/www/playground/public
└ /var/www/playground/.idea
Filters
You can define filters to filter your iteration. You can create custom filter easily in your Filter class and you can just define with an array., (*13)
$filters = [
[
'filter'=>'extension',
'extensions'=>['php', 'html', 'js', 'tpl']
],
[
'filter'=>'search_in_file',
'needle'=>'youtube'
]
];
$data = new HtmlDirectoryRenderer(
new LocalDirectoryIterator('/var/www/playground'),
$filters
);
$data->render();
Filters must return SPL directory File Info ( $this->directory ) or false (break out filter queue), (*14)
protected function ExtensionFilter($filter)
{
$extensions = $filter['extensions'];
return in_array($this->directory->getExtension(), $extensions) === true?$this->directory:false;
}