Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>Is it necessary to reduce the scope of OO programming when dealing with PHP?</p> </blockquote> <p>No. You just need to use <strong>lazy loading</strong> to instantiate parent player only if it becomes necessary.</p> <pre><code>Class Player { protected $id; protected $name; protected $parentId; protected $parent; public static function getById($id) { // fetch row from db where primary key = $id // instantiate Player populated with data returned from db } public function getParentPlayer() { if ($this-&gt;parentId) { $this-&gt;parent or $this-&gt;parent = Player::getById($this-&gt;parentId); return $this-&gt;parent; } return new Player(); // or null if you will } } </code></pre> <p>This way if you intantiate player id 40:</p> <pre><code>$john = Player::getById(40); </code></pre> <p>It does not have the $parent property populated. Only upon call to getParentPlayer() it is being loaded and stored under that property.</p> <pre><code>$joe = $john-&gt;getParentPlayer(); </code></pre> <p>That is of course only if $parentId is pointing to non-NULL.</p> <p><strong>Update:</strong> to solve problem of duplicate instances stored in protected property when two or more players share single parent, static cache can be used:</p> <pre><code> protected static $cache = array(); public static function getById($id) { if (array_key_exists($id, self::$cache)) { return self::$cache[$id]; } // fetch row from db where primary key = $id // instantiate Player populated with data returned from db self::$cache[$id] = ... // newly created instance // return instance } </code></pre> <p>If you expect to access significant number of parents on every request, it may be feasible to select all records from database at once and store them in another static pool.</p>
 

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