Note that there are some explanatory texts on larger screens.

plurals
  1. POIs changing an objects state/contents appropriate Iterator usage (php)
    primarykey
    data
    text
    <p>Consider an object used to store a collection of items, but that collection may vary depending on predefined contexts.</p> <pre><code>Class Container implements IteratorAggregate ( protected $contexts; // list of associated contexts, example: array(0=&gt;1,1=&gt;3) protected $contents; // array public loadContents( $contextId ) { /* populates $this-&gt;contents*/ } public getContexts() { /* populates $this-&gt;contexts */ } ... public function getIterator() { return new ArrayIterator($this-&gt;contents); } public getContextIterator() { return new contextIterator($this); } } </code></pre> <p>The iterator looks like:</p> <pre><code>Class contextIterator { protected $container; protected $contexts; protected $currentContext; public function __construct($container) { $this-&gt;container = $container; $this-&gt;contexts = $container-&gt;getContexts(); $this-&gt;currentContext = 0; } public current() { $this-&gt;container-&gt;loadContents( $this-&gt;key() ); return $this-&gt;contexts[ $this-&gt;key() ]; } public function key() { return $this-&gt;currentContext; } public function next() { $this-&gt;currentContext++; } public function rewind() { $this-&gt;currentContext = 0; } public function valid() { return isset( $this-&gt;contexts[ $this-&gt;key() ] ); } } </code></pre> <p>For the few cases where each context needs to be examined iteratively, I do the following:</p> <pre><code>$myContainer = new Container(); foreach( $myContainer-&gt;getContextIterator() as $key =&gt; $value ) { $myContainer-&gt;someMethod(); } </code></pre> <p>The above is nice and compact, but it feels dirty to me since I'm never actually using $key or $value. Is using the iterator overkill? Further, should an iterator ever change the state/contents of the object it is iterating?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload