Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think the citation you give has a good point but takes too hard a line.</p> <p>Your static method is what he calls a "leaf" method. In this case I think you are fine, as long as your static method doesn't have any external dependencies.</p> <p>The alternative is a data mapper, an object which is aware of the relationship between <code>User</code> and how it is stored in the database. Example:</p> <pre><code>class UserDBMapper { protected $pdo; protected $userclass; function __construct(PDO $pdo, $userclass) { $this-&gt;db = $db; // Note we can even dependency-inject a User class name if it obeys the interface that UserMapper expects. // You can formalize this requirement with instanceof, interface_exists() etc if you are really keen... $this-&gt;userclass = $userclass; } function getByPhone($phone) { // fetches users from $pdo $stmt = $this-&gt;db-&gt;query(...); $userinfo = $stmt-&gt;fetch().... // creates an intermediary structure that can be used to create a User object // could even just be an array with all the data types converted, e.g. your DateTimes. $userargs = array( 'name' =&gt; $userinfo['name'], 'created' =&gt; $userinfo['created'], // etc ); // Now pass this structure to the $userclass, which should know how to create itself from $userargs return new $this-&gt;userclass($userargs); } function save($userobj) { // save method goes in the Mapper, too. The mapper knows how to "serialize" a User to the DB. // User objects should not have find/save methods, instead do: // $usermapper-&gt;save($userobj); } } </code></pre> <p>This is a very powerful pattern (e.g., you need no longer have 1-1 type&lt;->table, instance&lt;->row correspondence like the Active Record pattern requires), and you can completely change your serialization method without altering your domain objects at all. It should also be obvious how much easier the mapper is to test. But in many cases this pattern is also over-engineered and more than you need. After all, most websites use the much simpler Active Record pattern.</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