Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Using chained methods in one single line like this</p> <pre><code>return $this-&gt;db-&gt;prepare("$query")-&gt;execute()-&gt;fetch(PDO::FETCH_OBJ)-&gt;$object; </code></pre> <p>is what <a href="https://en.wikipedia.org/wiki/Robert_Cecil_Martin" rel="nofollow">Robert Martin</a> calls "Train Wrecks" in <a href="http://books.google.de/books/about/Clean_Code.html?id=dwSfGQAACAAJ&amp;redir_esc=y" rel="nofollow">Clean Code (pg 98/99)</a>. It's hard to read and <em>"generally considered sloppy"</em> and should be avoided for the more readable</p> <pre><code>$statement = $this-&gt;db-&gt;prepare("$query"); $statement-&gt;execute(); $result = $statement-&gt;fetch(PDO::FETCH_OBJ); return $result-&gt;$object; </code></pre> <p>Please note that I corrected the code in the snippet above, as your one-liner will <strong>not</strong> work, because <a href="http://php.net/manual/de/pdostatement.execute.php" rel="nofollow"><code>execute</code> returns a boolean</a>, so you cannot call <code>fetch</code> on it:</p> <blockquote> <p><code>bool PDOStatement::execute ([ array $input_parameters ] )</code></p> </blockquote> <p>In other words, you cannot write this as a one-line statement anyway. </p> <p>Also note that Method Chaining is very often a violation of the <a href="https://en.wikipedia.org/wiki/Law_of_Demeter" rel="nofollow">Law of Demeter</a>, which states that</p> <blockquote> <p>a method M of an object O may only invoke the methods of the following kinds of objects:</p> <ul> <li>O itself</li> <li>M's parameters</li> <li>any objects created/instantiated within M</li> <li>O's direct component objects</li> <li>a global variable, accessible by O, in the scope of M</li> </ul> </blockquote> <p>Not following LoD usually leads to Mockfests in your UnitTests and makes your application tightly coupled to much more classes than necessary, which in turn impairs reusability and increases the time required for changes (among other things).</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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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