Re: Composition over inheritance: native support for "delegating" methods?
| From: | Levi Morrison | Date: | Mon, 22 Oct 2018 02:57:50 +0000 |
| Subject: | Re: Composition over inheritance: native support for "delegating" methods? | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-103356@lists.php.net to get a copy of this message | ||
I have wanted something like this before. I used a trait helper. This
worked for this domain because there is an interface that is well
established for the helper to use. Here's an example (written in my
email client, untested):
trait OuterIteratorHelper {
abstract function getInnerIterator(): \Iterator;
function rewind(): void { $this->getInnerIterator()->rewind(); }
function valid(): bool { return $this->getInnerIterator()->valid(); }
function next(): void { $this->getInnerIterator()->next(); }
function key() { return $this->getInnerIterator()->key(); }
function current() { return $this->getInnerIterator()->current(); }
}
final class TransformIterator implements \OuterIterator {
private $transformer, $inner;
function __construct(callable $transformer, \Iterator $inner) {
$this->transformer = $transformer;
$this->inner = $inner;
}
use OuterIteratorHelper;
function getInnerIterator() { return $this->inner; }
function current() {
return ($this->transformer)($this->inner->current());
}
}