[PSR-5] Iterator Typehinting

108 views
Skip to first unread message

Damian Mooyman

unread,
Aug 22, 2016, 12:44:54 AM8/22/16
to PHP Framework Interoperability Group
Hello, I understand that at this time PSR-5 is lacking a sponsor, but I trust that it's ok for us to continue discussing ideas.

I would like to add to the list of open issues (from https://groups.google.com/forum/#!searchin/php-fig/psr-5%7Csort:relevance/php-fig/Rg4fugqGyzU/muMXYZPTeWEJ) a proposal to support a standard phpdoc syntax for typed iterators.

I consider this to really be a separate (but related) discussion to the generics proposal at https://groups.google.com/forum/#!msg/php-fig/lSfzx7Ubstc/6vjz3ILThS0J;context-place=forum/php-fig

Out in the wild, I've seen two alternative approaches that can be applied at the class-level to apply typing to iterators.

1. PHPStorm has a non-standard __iterator method https://youtrack.jetbrains.com/issue/WI-18972
2. IteratorAggregate subclasses can override the getIterator() method hinting, as commented at https://github.com/php-fig/fig-standards/pull/169#issuecomment-46590615

However the problems with the above are, 1. __iterator() isn't a real (or magic) method, and 2. getIterator() actually returns an object of type Traversable or Iterator, and thus overriding these with another type is not strictly correct.

If I wish to propose an explicit syntax, is it ok for me to discuss it here, or should I open this on github? I could PR to the current PSR-5 if that's the best way to propose a change, maybe after a little bit of pre-discussion.

Thanks for hearing me out, and I hope I can actually start contributing to the group for once. :)

Kind regards,

Damian Mooyman | SilverStripe

Damian Mooyman

unread,
Aug 22, 2016, 3:46:23 AM8/22/16
to PHP Framework Interoperability Group
Thinking about this a bit more, perhaps we could leverage another suggested extension, rather than adding a new separate convention.



 
/**
  * @mixin MyObject[]
  */

 
class MyObjectCollection implements IteratorAggregate {
     
// ...
 
}



In effect, this collection inherits the same hinting from "a typed collection of MyObject instances", so the usage makes sense. It also separates the declaration from any method or property specific components, which would more than likely vary from object to object.

Just to get the ball rolling. :)
Reply all
Reply to author
Forward
0 new messages