<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Eduar Carvajal on Medium]]></title>
        <description><![CDATA[Stories by Eduar Carvajal on Medium]]></description>
        <link>https://medium.com/@eduar.carvajal?source=rss-36b2970fd585------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fQu5MrCVVhMfXZkOnJWvqw.jpeg</url>
            <title>Stories by Eduar Carvajal on Medium</title>
            <link>https://medium.com/@eduar.carvajal?source=rss-36b2970fd585------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 18:20:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eduar.carvajal/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Generating PHP code to optimize execution]]></title>
            <link>https://medium.com/brainz-engineering/generating-php-code-to-optimize-execution-7001ca58fe26?source=rss-36b2970fd585------2</link>
            <guid isPermaLink="false">https://medium.com/p/7001ca58fe26</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Eduar Carvajal]]></dc:creator>
            <pubDate>Wed, 18 Jan 2017 21:11:09 GMT</pubDate>
            <atom:updated>2017-02-14T23:49:47.967Z</atom:updated>
            <content:encoded><![CDATA[<p>Here at <a href="https://brainz.co/">Brainz</a> we employ an <a href="https://en.wikipedia.org/wiki/Object-relational_mapping">Object Relational Mapper (ORM)</a> for PHP to access database records in an object-oriented fashion. Basically what an ORM does is expose records as PHP instances of pre-defined structures or classes called models or entities. These models allow us to define a static structure that mirrors a collection or table within the database.</p><p>For instance, the next model describes a model called “categories”:</p><pre>&lt;?php</pre><pre>namespace Game\Models;<br><br>/**<br> * @Source(&quot;cc_categories&quot;)<br> */<br>class Categories<br>{<br>    /**<br>     * @Attribute(type=&quot;id&quot;, primary=true)<br>     */<br>    private $id;<br><br>    /**<br>     * @Attribute(type=&quot;string&quot;, nullable=true)<br>     */<br>    private $name;<br><br>    public function getId()<br>    {<br>        return $this-&gt;id;<br>    }<br><br>    public function setId($id)<br>    {<br>        $this-&gt;id = $id;<br>    }<br><br>    public function getName()<br>    {<br>        return $this-&gt;name;<br>    }<br><br>    public function setName($name)<br>    {<br>        $this-&gt;name = $name;<br>    }    <br>}</pre><p>The model “categories” maps a collection in the database called “cc_categories”. It doesn’t matter what name of the mapped collection is, we can simply refer to the class name we chose within the application instead of the collection name. Using annotations we describe the structure of the collection, which in this case are only two fields each one with its corresponding data type and nullability. The default visibility of these fields is private which implies that setters and getters are required to access and modify the values of the collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*7DnYpnVPVywZpqz6MZxpBA.png" /></figure><p>Once a record is retrieved from the database is necessary hydrate an instance for every record obtained:</p><pre>$category = $this-&gt;getEntityManager()-&gt;findOne(Categories::class);<br>echo $category-&gt;getName();</pre><p>To perform this simple task the ORM has to connect to the database, query the first record in the collection and then instantiate the model that represents the record in the proper collection. For each field available in the model the ORM has to assign the corresponding retrieved value.<br>Hydrating an instance means that a value got from the database must be dynamically assigned using the field’s setter.</p><p>Normally the hydrating process is performed the easiest way possible using <br><a href="http://php.net/manual/es/book.reflection.php">Reflection</a>. By introspecting the fields declared in the classes we can get the structure required by the application. Taking advantage of the dynamic nature of PHP we assign and retrieve values from and to a class instance. The following snippet explains the process in a simplified way:</p><pre>$reflection = new ReflectionClass(Categories::class);<br><br>$category = new Categories();<br>foreach ($reflection-&gt;getProperties() as $field) {<br>    $method = &quot;set&quot; . $field;<br>    $category-&gt;{$method}($data[$field]);<br>}</pre><p>While the above process works in principle it is not satisfactory in practice, often using reflection incurs in a high memory usage, further dynamic method calls are usually slower that direct method calls. If we require to handle a high volume of data it’s very likely that this impacts performance considerably.</p><p>Ideally to avoid this overhead the hydration must be done directly as below:</p><pre>$category = new Categories();    <br>$category-&gt;setId($data[&quot;id&quot;]);<br>$category-&gt;setName($data[&quot;name&quot;]);</pre><h4>Generating code</h4><p>Looking for a solution to improve the performance we concluded that somehow we should force our application to perform direct assignation with no developer involvement. To achieve this we birth a PHP source code generator for hydration.</p><p>Using an automatic code generation helper we started forging hydrator classes per model. An hydrator is a very simple class that is in charge of assigning values that come from the database. An hydrator class looks like the following:</p><pre>class CategoriesHydrator<br>{<br>    public static hydrate(array $data)<br>    {<br>        $category = new Categories();    <br>        $category-&gt;setId($data[&quot;id&quot;]);<br>        $category-&gt;setName($data[&quot;name&quot;]);<br>        return $category;<br>    }<br>}</pre><p>So when we need to hydrate an instance of categories we simply call its hydrator that assigns every property without relying on reflection but direct assignment. Hydrators must be generated automatically by the ORM. If a model changes anytime in its structure the ORM must detect these modifications and generate the hydrator helper once again.</p><p>The PHP source code generation for an hydrator involves:</p><ol><li>Validate whether the model’s “hydrator” exists or not.</li><li>In case that a model doesn’t exist or it has changed relative to the previously generated version generate it again applying reflection to refresh the changes in the hydrator.</li><li>Using “autoloading” load the hydrator class and call the hydrate method to create a new instance</li><li>…</li><li>Profit</li></ol><h4>Benchmark</h4><p>We made a comparison between hydrating using reflection and direct assignment using hydrator classes showing the following results:</p><pre>Reflection 0.3272<br>Direct Assignment 0.1450</pre><p>By using direct assignment through hydrators we achieve 44% improvement compared to dynamic assignment. We make use of <a href="http://php.net/manual/es/book.opcache.php">opcache </a>in our production servers, it clearly helps it to do a better job in case of adopting<br>direct assignment.</p><h4>Conclusion</h4><p>We can conclude that when we were working with reflection we had an important increment of execution time caused by dynamic assignation, this increase was directly proportional to the number of properties and records retrieved from the database in certain point. However, using direct assignment we could increase the performance considerably when we handle high volumes of data. We hope this technique will be useful for your own developments to get the most out of PHP, also, you can apply this methodology to other interprete languages.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7001ca58fe26" width="1" height="1" alt=""><hr><p><a href="https://medium.com/brainz-engineering/generating-php-code-to-optimize-execution-7001ca58fe26">Generating PHP code to optimize execution</a> was originally published in <a href="https://medium.com/brainz-engineering">Brainz Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>