<?php function *readXML($file) { $r = new XMLReader; $r->open($file); while($r->read()) { yield $r; } } function *filterNodes(callable $predicate, $nodes) { foreach($nodes as $node) if($predicate($node)) yield $node; } function matchName($name) { return function($node) use($name) { return $node->name === $name; }; }
<?php function *getArticlesFromXML($file) { foreach(filterNodes(matchName('article'), readXML($file)) as $node) yield nodeToArticle($node); } function nodeToArticle($node) { // transform node return $node->name; } $articles = [foreach(getArticlesFromXML('data.xml') as $article) yield $article];
XMLReader
will understand how the control over parsing was taken from the while
, and “adjusted” to the declarative style using higher order functions. <?php // inside some class public function getResult() { return SomeCustomIterator($this->results, new SomeCustomDecorator); } // with generators public function *getResults() { foreach($this->results as $result) yield new SomeCustomDecorator($result); }
<?php function select() { return func_get_args(); } function from($source) { return $source; } function where() { return func_get_args(); } function *query($select, $from, $where) { foreach($from as $element) { foreach($where as $predicate) { if(false === $predicate($element)) continue 2; } $fields = array(); foreach($select as $selector) { $fields[] = $selector($element); } yield $fields; } } $articles = query( select(property('name')), from(readXML('data.xml')), where(matchName('article')) ); // where property could be something as simple as function property($name) { return function($node) use ($name) { return $node->{$name}; }; }
$ git clone -b addListComprehensions https://github.com/nikic/php-src.git $ cd php-src $ ./buildconf $ ./configure $ make cli $ ./sapi/cli/php some-example-file.php
Source: https://habr.com/ru/post/147885/
All Articles