It is easy if such interface already extends some kind of iterator...

interface Stream extends IteratorAggregate
{
    /**
     * @return Item[]
     */
    public function getIterator();
}

...or... 

interface Stream extends Iterator
{
    /**
     * @return Item
     */
    public function current();
}

...so IDEs have no problems with inferring actual type that variable of 
type `Stream` iterates over...

/* @var $stream Stream */
foreach ($stream as $item) {
    $item->... // works, *Item* class methods are suggested
}

...but what if we want to delay the decision of iteration mechanism? Like...

interface Stream extends Traversable
{}

...so later on we can do this:

class InMemoryStream implements Stream, IteratorAggregate
{
    public function __construct(Item ...$items)
    {
        $this->items = $items;
    }

    // rest of the code goes here

    /**
     * @return Item[]
     */
    public function getIterator()
    {
        return new ArrayIterator($this->items);
    }
}

class DatabaseStream implements Stream, Iterator
{
    // rest of the code goes here

    public function rewind()
    {
        $this->statement = $this->connection->prepare('SELECT * FROM items'
);
        $this->statement->execute();
        $this->current = $this->statement->fetch(\PDO::FETCH_ASSOC);
        $this->key = 0;
    }

    public function next()
    {
        $this->current = $this->statement->fetch(\PDO::FETCH_ASSOC);
        $this->key++;
    }
    
    public function key()
    {
        return $this->key;
    }
    
    public function valid()
    {
        return false !== $this->current;
    }

    /**
     * @return Item
     */
    public function current()
    {
        return new Item($this->current);
    }
}

Unfortunately IDEs, as can be expected, can't handle this.

/* @var $stream Stream */
foreach ($stream as $item) {
    $item->... // not enough information for IDEs to suggest type that 
$stream iterates over.
}

AFAIK at this moment the only solution for such case is to annotate 
variables in user-land... every time.

/* @var $stream Stream|A[] */
foreach ($stream as $item) {
    $item->... // works
}

// or worse

/* @var $stream DatabaseStream */
foreach ($stream as $item) {
    $item->... // works but annotation specifies actual implementation 
which violates Design by Contract principle
}



It bugs me personally, but I would like to hear your opinion on this and 
possible solution.

-- 
You received this message because you are subscribed to the Google Groups "PHP 
Framework Interoperability Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to php-fig+unsubscr...@googlegroups.com.
To post to this group, send email to php-fig@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/php-fig/00521ff4-39ed-45a1-a15c-3df0090c89ad%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to