Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is simple function to populate object members without making class members public. It also leaves constructor for your own usage, creating new instance of object without invoking constructor! So, your domain object doesn't depend on database!</p> <hr> <pre><code>/** * Create new instance of a specified class and populate it with given data. * * @param string $className * @param array $data e.g. array(columnName =&gt; value, ..) * @param array $mappings Map column name to class field name, e.g. array(columnName =&gt; fieldName) * @return object Populated instance of $className */ function createEntity($className, array $data, $mappings = array()) { $reflClass = new ReflectionClass($className); // Creates a new instance of a given class, without invoking the constructor. $entity = unserialize(sprintf('O:%d:"%s":0:{}', strlen($className), $className)); foreach ($data as $column =&gt; $value) { // translate column name to an entity field name $field = isset($mappings[$column]) ? $mappings[$column] : $column; if ($reflClass-&gt;hasProperty($field)) { $reflProp = $reflClass-&gt;getProperty($field); $reflProp-&gt;setAccessible(true); $reflProp-&gt;setValue($entity, $value); } } return $entity; } /******** And here is example ********/ /** * Your domain class without any database specific code! */ class Employee { // Class members are not accessible for outside world protected $id; protected $name; protected $email; // Constructor will not be called by createEntity, it yours! public function __construct($name, $email) { $this-&gt;name = $name; $this-&gt;emai = $email; } public function getId() { return $this-&gt;id; } public function getName() { return $this-&gt;name; } public function getEmail() { return $this-&gt;email; } } $row = array('employee_id' =&gt; '1', 'name' =&gt; 'John Galt', 'email' =&gt; 'john.galt@whoisjohngalt.com'); $mappings = array('employee_id' =&gt; 'id'); // Employee has id field, so we add translation for it $john = createEntity('Employee', $row, $mappings); print $john-&gt;getName(); // John Galt print $john-&gt;getEmail(); // john.galt@whoisjohngalt.com //... </code></pre> <hr> <p>P.S. Retrieving data from object is similar, e.g. use $reflProp->setValue($entity, $value); P.P.S. This function is heavily inspired by <a href="http://www.doctrine-project.org/projects/orm.html" rel="nofollow noreferrer">Doctrine2 ORM</a> which is awesome!</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