On Wed, Feb 17, 2016 at 7:25 AM, Kevin Gessner <kgess...@etsy.com> wrote: > Hello internals team! I'd like to propose an RFC to allow traits to > implement interfaces. > > I've noticed s pattern in Etsy's code and elsewhere, where a trait provides > a common implementation of an interface. Classes that use the trait are > required to also explicitly declare the interface to benefit. I propose > that traits be permitted to declare and implement interfaces. Classes that > use such a trait would then implement the interface, as though it were > declared on the class, without declaring the interface explicitly.
I am unsure on the particular detail of the class automatically implementing the interface. I want to add my personal experience with traits: every time I create a trait it is to implement an interface. Here is a publicly available [example with OuterIterator](https://github.com/morrisonlevi/Ardent/blob/master/src/Collection/OuterIteratorTrait.php): trait OuterIteratorTrait { abstract function getInnerIterator() : Iterator; function current() { return $this->getInnerIterator()->current(); } function next(): void { $this->getInnerIterator()->next(); } function key() { return $this->getInnerIterator()->key(); } function valid(): bool { return $this->getInnerIterator()->valid(); } function rewind(): void { $this->getInnerIterator()->rewind(); } } This makes it really easy to implement iterators. The class that uses the trait can simply implement `getInnerIterator` and then modify only the methods that differ from standard behavior. Here are a few examples: * https://github.com/morrisonlevi/Ardent/blob/master/src/Collection/HashMapIterator.php * https://github.com/morrisonlevi/Ardent/blob/master/src/Collection/HashSetIterator.php * https://github.com/morrisonlevi/Ardent/blob/master/src/Collection/SortedMapIterator.php * https://github.com/morrisonlevi/Ardent/blob/master/src/Collection/SortedSetIterator.php I can see how it would be nice to allow the trait to officially declare that it implements some interface (in this case Iterator or OuterIterator) which would require that the trait has fully implemented the required methods (or declared them as abstract). This would be a small improvement but helpful. I am less certain about the classes which `use` it automatically inheriting the interfaces. To clarify: I am neither in favor or against that part. Or at least at this stage, anyway. -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php