<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Juozas devBlog &#187; PHP</title>
	<atom:link href="http://dev.juokaz.com/category/php/feed" rel="self" type="application/rss+xml" />
	<link>http://dev.juokaz.com</link>
	<description>Random ideas, scripts and facts</description>
	<lastBuildDate>Mon, 22 Mar 2010 10:48:42 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>ACL made easy. Part 1</title>
		<link>http://dev.juokaz.com/php/acl-made-easy-part-1</link>
		<comments>http://dev.juokaz.com/php/acl-made-easy-part-1#comments</comments>
		<pubDate>Mon, 22 Mar 2010 10:48:42 +0000</pubDate>
		<dc:creator>Juozas</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[acl]]></category>
		<category><![CDATA[doctrine]]></category>
		<category><![CDATA[zend framework]]></category>
		<category><![CDATA[zend_acl]]></category>

		<guid isPermaLink="false">http://dev.juokaz.com/?p=1011</guid>
		<description><![CDATA[Every now and then I see questions about ACL and how to use it. A lot of web developers are using it without actually knowing what it is and how it works, even though it&#8217;s powering one of the most important part of applications &#8211; user access management. So this series will explain that from [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://dev.juokaz.com/wp-content/uploads/2010/03/accessdenied-300x291.png" alt="" title="access denied" width="150" height="145" class="alignnone size-medium wp-image-1015" />Every now and then I see questions about <a href="http://en.wikipedia.org/wiki/Access_control_list">ACL</a> and how to use it. A lot of web developers are using it without actually knowing what it is and how it works, even though it&#8217;s powering one of the most important part of applications &#8211; user access management. So this series will explain that from raw basics to complete implementation with Zend Framework component <a href="http://framework.zend.com/manual/en/zend.acl.html">Zend_Acl</a>.</p>
<h5>What is ACL?</h5>
<p>ACL is the last step you make with implementing users&#8217; access control &#8211; you first start with basic PHP website, then add login for users to post comments, then you create admin interface for administrators, some user groups to access private data etc. Probably you&#8217;ve seen code like this:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">type</span> <span style="color: #339933;">==</span> ADMIN<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$html</span> <span style="color: #339933;">.=</span> <span style="color: #0000ff;">'&lt;a href=&quot;/index.php?delete='</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$id</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&quot;&gt;&lt;/a&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>It works fine, but the problem is that it becomes very difficult to extend as all access rules are stored in places all over the code, hence changing it isn&#8217;t that easy. It&#8217;s also not &#8220;correct&#8221;, as with all things in programming, things (logic) should be <a href="http://en.wikipedia.org/wiki/Encapsulation_(computer_science)#Encapsulation">encapsulated</a>. This problem is solved by using ACL, which makes code to look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>user_can<span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'page'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'delete'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$html</span> <span style="color: #339933;">.=</span> <span style="color: #0000ff;">'&lt;a href=&quot;/index.php?delete='</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$id</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&quot;&gt;&lt;/a&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This code does exactly the same, but actual permissions logic is hidden (encapsulated) inside. It&#8217;s very clear what it is doing  &#8211; can user <em>$user</em> execute <em>delete </em>on <em>page</em>? It doesn&#8217;t show that ACL is used at all, but this is a first step towards right direction. </p>
<p>Outside code shouldn&#8217;t care how these permissions are being calculated, as long as that one entry point is used (in this case a function <em>user_can</em>) pretty much any logic can lie inside, even the same as shown in first example, but when needed a proper ACL layer can be added, so lets look at that. </p>
<h5>Basics</h5>
<p>ACL stands for &#8220;<a href="http://en.wikipedia.org/wiki/Access_control_list">Access control list</a>&#8221; and it is a system designed to deal with any complexity permissions specifications. ACL systems consist of three basic components: roles, resources and permissions. They form a <a href="http://en.wikipedia.org/wiki/Graph_theory">graph</a> and are as follows:</p>
<ul>
<li><strong>Roles</strong> &#8211; &#8220;admin&#8221;, &#8220;editors&#8221; etc. User has one or more roles, depending on architecture.</li>
<li><strong>Resources</strong> &#8211; &#8220;product#123&#8243;, &#8220;categories&#8221; etc. It&#8217;s just an object which is controlled by ACL.</li>
<li><strong>Privileges</strong> &#8211; &#8220;list&#8221;, &#8220;delete&#8221;, &#8220;create&#8221; etc. Actions <em>role </em>can perform on <em>resource</em>.</li>
</ul>
<p>Once you have these components defined you can start forming relations. For example, string &#8220;admin can delete products&#8221; can be seen as: <em>role</em> &#8220;admin&#8221; has <em>privilege</em> &#8220;delete&#8221; on <em>resource </em>&#8220;products&#8221;.</p>
<p>One thing to understand from this is that all 3 components are very dynamic &#8211; I don&#8217;t know about any situation where ACL cannot be applied, it&#8217;s only a matter of understanding how it works. For example Zend_Acl relies on you for constructing ACL tree, so DB backend, lazy-loading etc. should be created yourself, that&#8217;s why it&#8217;s too hard to start with and why I&#8217;m writing this in a first place. </p>
<h5>Web</h5>
<p>MVC is very easy to use with ACL, as you have a very clean separation of resources &#8211; every controller (or controller and module) is a resource and privileges are usually controllers&#8217; actions. For example products controller can have &#8220;list&#8221;, &#8220;add&#8221;, &#8220;edit&#8221; and &#8220;delete&#8221; actions and those clearly are permissions on products resource.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$acl</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">isAllowed</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span><span style="color: #339933;">,</span> <span style="color: #000088;">$request</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getController</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$request</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getAction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Looks very clean and logical. Of course direct mapping from controller/action name to resource and privilege is not perfect; ideally you should construct some <em>Zend_Acl_Resource</em> object from request data and check on it. As you will see in later posts, you can use same logic to auto-generate menus only including links user can actually see. </p>
<p>Quite commonly resources are much smaller and represent actual objects in system &#8211; news item, product, comment etc. Some users can only delete their own comments, where user belonging to sport news admin group can delete any in that category. Even though these rules are very different for different apps, but actual ACL implementation is pretty much the same &#8211; just create resources for each object (or lazy load) and add some permissions logic depending on requirements.</p>
<h5>Problems</h5>
<p>ACL management is problematic when you do not have GUI for that. This is because ACL is a complicated <a href="http://en.wikipedia.org/wiki/Graph_theory">graph</a> and just by looking at the code it&#8217;s very hard to understand how all elements are connected to each other.  </p>
<p>One of the biggest causes of problematic ACL is the fact that it supports inheritance and privileges have <em>weird</em> inheritance by themselves (I don&#8217;t know how much of this applies to ACL in general; later observations are mainly based on Zend_Acl behaviour). For example if role has access to resource with permission &#8220;<em>null</em>&#8220;, user can access resource with any permission (even if there is no information about it). Whereas with resources, ACL system checks parent resource until it finds allow/deny.</p>
<p>Because of those issues, one of the first things I recommend doing is&#8230; unit test. It&#8217;s not that hard, but can help you to understand how everything works and if in fact ACL tree represents your required logic. Once you know that it does work in backend, create user interface (like seen in many CMS systems) to make management easy and clean. Ideally you shouldn&#8217;t touch it once it&#8217;s created.</p>
<h5>Conclusion</h5>
<p>ACL is very powerful system (if your library supports all features of course), although it&#8217;s definitely not the easiest one to work with. In next posts of this series I&#8217;m going to look at actual implementations and how to make use of them.</p>
<p><strong>All parts</strong>:</p>
<ol>
<li><a href="http://dev.juokaz.com/php/acl-made-easy-part-1">ACL made easy. Part 1</a></li>
</ol>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.juokaz.com/php/acl-made-easy-part-1/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Zend Framework is NOT bloated</title>
		<link>http://dev.juokaz.com/php/zend-framework-is-not-bloated</link>
		<comments>http://dev.juokaz.com/php/zend-framework-is-not-bloated#comments</comments>
		<pubDate>Fri, 12 Mar 2010 17:14:21 +0000</pubDate>
		<dc:creator>Juozas</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[apc]]></category>
		<category><![CDATA[bloated]]></category>
		<category><![CDATA[features]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[optimization]]></category>
		<category><![CDATA[padraic]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[slow]]></category>
		<category><![CDATA[zend framework]]></category>
		<category><![CDATA[zf]]></category>

		<guid isPermaLink="false">http://dev.juokaz.com/?p=993</guid>
		<description><![CDATA[ Zend Framework is always considered as being the slow/bloated one. I don&#8217;t think this is right, so I decided to prove that it&#8217;s not correct and in fact ZF is as good as other frameworks are. This post doesn&#8217;t cover any benchmarks though; this is more like a architecture review and some misconceptions disproof. [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-460" title="Zend Framework" src="http://dev.juokaz.com/wp-content/uploads/2009/04/logo-zend-framework.jpg" alt="Zend Framework" width="169" height="114" /> Zend Framework is always considered as being the slow/bloated one. I don&#8217;t think this is right, so I decided to prove that it&#8217;s not correct and in fact ZF is as good as other frameworks are. This post doesn&#8217;t cover any benchmarks though; this is more like a architecture review and some misconceptions disproof.  </p>
<p>Before we go any further, let&#8217;s check with <a href="http://en.wikipedia.org/wiki/Software_bloat">Wikipedia</a>:</p>
<blockquote><p>Software bloat is a term used to describe the tendency of newer computer programs to have a <strong>larger installation footprint</strong>, or have many <strong>unnecessary features</strong> that are not used by end users, or just generally <strong>use more system resources</strong> than necessary, while offering little or <strong>no benefit</strong> to its users.
</p></blockquote>
<p>So what I need to provide is <em>contra</em> arguments that Zend Framework doesn&#8217;t do those.</p>
<h5>&#8220;Large installation footprint&#8221;</h5>
<p>25.8 MB and 2338 files. This is how much ZF <em>weights</em> and this is usually quoted as the main factor of bloatedness. First of all, 25.8 MB is a joke &#8211; full application takes maximum 50 MB. So unless you want to squeeze in 100&#8217;s of projects into a shared hosting, size of ZF shouldn&#8217;t matter at all. Price of hard-drive and RAM (for APC caches) is so low nowadays, that I don&#8217;t even remember last time I checked how much space my project takes up.</p>
<p>Same applies with files count &#8211; why would anyone even care how much files it has? As you probably know, PHP doesn&#8217;t compile your project into one binary, thus making it a big file. What it does, is it loads external code using include/require statements. Hence, from those 2338 you usually going to use around 300 (based on my tests). One can argue that this is still a lot of files, but this <em>big </em>number of files comes from ZF extensibility. A lot of functionality is separated into plugins, adapters etc. </p>
<h5>&#8220;Unnecessary features&#8221;</h5>
<p>ZF has massive amount of functionality: starting from web framework components and finishing up with services classes (I have written more about this <a href="http://dev.juokaz.com/php/why-zend-framework">here</a>). There is a big chance that you are not going to use all of them, but because all components are decoupled (as much as possible) and as mentioned above, you don&#8217;t even notice them if you don&#8217;t include those files. </p>
<p>I&#8217;m one of those people who think that ZF has too much components, but this is rather my own personal preference rather than a problem. Nevertheless, I haven&#8217;t used only a few of available components as once you need something, it&#8217;s always very quick to just <em>use</em> it. No need to download anything more or look for available components. For serious components like <a href="http://dev.juokaz.com/php/zend-framework-and-doctrine-part-1">Doctrine</a>, you probably want to look around, but just for some regular code Zend provides all required features.</p>
<h5>&#8220;Use more system resources&#8221;</h5>
<p>This one is <strong>hot</strong> topic in ZF world. But the point here is that &#8220;features = slow&#8221;, especially in PHP. This happens because PHP as a language is not <em>that</em> fast and as you start adding more features and code, you get slower code. This where framework&#8217;s benchmarks are born, but as Pádraic mentions in his <a href="http://blog.astrumfutura.com/archives/421-PHP-Framework-Benchmarks-Entertaining-But-Ultimately-Useless.html">post</a> about benchmarks: </p>
<blockquote><p>To create a positive benchmark, you need to understand that all frameworks were born as festering piles of unoptimised stinking crap. They were all born bad and get worse with age. This sounds quite sad, but actually it&#8217;s an inevitable compromise between performance and features. It&#8217;s also a compromise between performance and ease-of-use</p></blockquote>
<p>It&#8217;s inevitable to provide those features that ZF provides and still work faster than other frameworks. So considering the speed of development you need to know how much performance you actually need. Maybe rapid development is much more important? At least it&#8217;s for me, and by sacrificing some tenths of a second I can roll out projects in a few days. And as &#8220;bloated&#8221; definition states, something is not bloated if it provides benefits while using more system resources.</p>
<h5>How to make it not bloated?</h5>
<p>If you still consider ZF as bloated framework, let me give you some ideas how to make it work for you. First of all &#8211; <a href="http://en.wikipedia.org/wiki/Software_performance_analysis">profile</a>, profile, profile! I keep mentioning this every time I talk about performance, but don&#8217;t judge performance of something without actually knowing <em>why</em> it&#8217;s not performing well. <a href="http://xdebug.org/">Xdebug</a> helps here as it can provide profiling data, which you then can use to detect slow parts of code. From my experience this is usually I/O &#8211; DB calls, file reads etc. Get rid of those and you have some decent performance increase. </p>
<p>A lot of other performance factors come from knowing how framework works internally or <em>really</em> reading manual. For example <a href="http://framework.zend.com/manual/en/zend.application.html">Zend_Application</a> is kind of slow, but it can be easily optimized by just getting rid of it. But this is only needed if you are running very big application, where every millisecond of execution matters, for normal application you&#8217;d hardly get any benefit. This is very ZF&#8217;s decoupled components start to shine, as you can just use those which work well and add some special sauce for other parts.  </p>
<h5>Conclusion</h5>
<p>I use Zend Framework extensively, so I&#8217;m biased a lot here, but having this much of experience, I can at least judge it objectively (up to some degree). And what I can say is that ZF is not bloated, it can be slower than some other available frameworks, but widely popular method to judge its performance by the number of files it has is just wrong. Of course it&#8217;s not the easiest framework to get working with (and get it to perform efficiently), but don&#8217;t get put off just by archive size it comes in. </p>
]]></content:encoded>
			<wfw:commentRss>http://dev.juokaz.com/php/zend-framework-is-not-bloated/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t be afraid of PHP 5.3</title>
		<link>http://dev.juokaz.com/php/dont-be-afraid-of-php-5-3</link>
		<comments>http://dev.juokaz.com/php/dont-be-afraid-of-php-5-3#comments</comments>
		<pubDate>Tue, 02 Mar 2010 12:37:34 +0000</pubDate>
		<dc:creator>Juozas</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Servers]]></category>
		<category><![CDATA[backwards compatibility]]></category>
		<category><![CDATA[debian]]></category>
		<category><![CDATA[doctrine]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[php 5.3]]></category>
		<category><![CDATA[server]]></category>
		<category><![CDATA[symfony]]></category>

		<guid isPermaLink="false">http://dev.juokaz.com/?p=977</guid>
		<description><![CDATA[While attending PHPUK conference in London, I noticed how much talk there is about PHP 5.3 and &#8220;when to upgrade?&#8221;, there was even a presentation about that. Because I have been using PHP 5.3 for more than half a year, I decided to share my views on this topic. This topic is very important as [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://dev.juokaz.com/wp-content/uploads/2009/05/osoft_1490922690php-logo-300x158.png" alt="" title="osoft_1490922690php-logo" width="150" height="79" class="alignnone size-medium wp-image-800" style="float: left; margin-right: 10px;" />While attending <a href="http://www.phpconference.co.uk/">PHPUK conference</a> in London, I noticed how much talk there is about PHP 5.3 and &#8220;when to upgrade?&#8221;, there was even a presentation about that. Because I have been using PHP 5.3 for more than half a year, I decided to share my views on this topic. This topic is very important as the earlier PHP 5.3 is adopted, the sooner second iteration of frameworks can be released (story for <a href="http://www.symfony-project.org/blog/2009/10/27/why-will-symfony-2-0-finally-use-php-5-3">Symfony</a>).</p>
<h5>New features</h5>
<p>PHP 5.3 includes a lot of <a href="http://php.net/releases/5_3_0.php">new features</a>. Some of them are new language features like namespaces, closures, exceptions chaining, jump labels etc., and even though these are very recommended to learn, they are not required. You can continue to write code as you are used to and chances are that it will still work (more about that in <em>Legacy code</em>). </p>
<p>What is important from new features is fixes are enhancements. For example new garbage collector and other fixes reduce memory usage and increases performance. There are also some new extensions like <a href="http://php.net/phar">phar</a>, <a href="http://php.net/sqlite3">sqlite3</a> and <a href="http://php.net/fileinfo">fileinfo</a> and some libraries (like mysql or openssl) have some major improvements. Finally, Windows support is improved even further and now is expected to be even more production-ready.</p>
<h5>Legacy code</h5>
<p>Apparently the biggest problem is with legacy applications &#8211; somehow everyone just decided that because of all these new features, everything should break. If you&#8217;d look at backward incompatibility list <a href="http://php.net/manual/en/migration53.incompatible.php">here</a>, you notice that not that much has changed. Or in other words &#8211; if your code was <em>&#8220;correct&#8221;</em> before upgrade, it will work fine with PHP 5.3 too. For example static and/or private setters, ereg and some more other features shouldn&#8217;t have been used in a first place as manual clearly stated that.</p>
<p>Personally I have upgraded around 10 projects to run on PHP 5.3, each took less than an hour. On my development machine I also have <a href="http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting">strict</a> error reporting level so I even had to remove marked-as-deprecated code, but for larger part of code everything worked fine. Furthermore, some of that code has been written using PHP 4, a couple years ago, and it still worked just fine. </p>
<h5>Debian&#8230;</h5>
<p>As far as I&#8217;m aware of, main linux distros like Debian or Red Hat do not have PHP 5.3 in their <em>stable</em> repositories, which makes upgrading potentially very hard or impossible. I have come across this before &#8211; sysadmins do not want to install anything outside from stable, so the only option is to wait (that happened to me when PHP 5 was still not well adopted). This is probably the only reasonable argument to not switch to PHP 5.3, but only if you don&#8217;t have option to switch servers.</p>
<p>I&#8217;m lucky with this problem, because I do not administer servers, but still can request for any PHP version I want. If you do not have this option, maybe it&#8217;s time to switch hosting server provider? There can be different situations, but software version shouldn&#8217;t be a limiting factor, especially when new version is available and known to be stable enough. You can even use <a href="http://www.top-web-solutions.com/apache-with-multiple-php-versions.html">multiple PHP versions</a> if switching server would require testing a lot of applications.</p>
<h5>Why you should be using PHP 5.3 right now</h5>
<p>Firstly because it has those new features, which mean that you can start to use them as an early adopter and benefit later. All <em>second iteration</em> frameworks (Zend Framework 2.0, <a href="http://symfony-reloaded.org/">Symfony 2.0</a>, Lithium etc.) coming out late this year will use PHP 5.3 extensively, so knowing how namespaces work (I&#8217;d say they are the ones you need to look first) and how to utilize closures will mean that you can get going very quickly. </p>
<p><a href="http://www.doctrine-project.org/documentation/2_0/en">Doctrine 2.0</a> is probably the best example of why you should learn PHP 5.3 now &#8211; most of its features could be written in older versions too, but not as clean and easy to understand. And it&#8217;s already in <em>alpha</em> stage, so stable version might be coming out very soon and yet again &#8211; if you want to stay on top of your game, you need to know how it works and how to leverage all new features. </p>
<p>As mentioned above, because of new garbage collector implementation PHP 5.3 performs much better (<a href="http://schlueters.de/blog/archives/68-PHP-5.3-Up-to-30-performance-win.html">benchmarks</a>). From my personal tests I have noticed that Zend Framework uses much less memory, just because there is less <a href="http://en.wikipedia.org/wiki/Memory_leak">memory leaks</a>, Doctrine of course gets a big <a href="http://dev.juokaz.com/php/zend-framework-and-doctrine-part-3">speed up</a> too.</p>
<h5>Conclusion</h5>
<p>I&#8217;m yet unsure what is all that buzz about &#8211; PHP 5.3 is stable, way faster than previous versions and works with legacy code just fine. Considering that it has new core features, which will be expected from developers to be known in just a few months, I don&#8217;t see a reason why you shouldn&#8217;t use it. And if you have any questions you can just ask me directly on <a href="http://twitter.com/juokaz">twitter</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.juokaz.com/php/dont-be-afraid-of-php-5-3/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Zend Framework tips and tricks</title>
		<link>http://dev.juokaz.com/php/zend-framework-tips-and-tricks</link>
		<comments>http://dev.juokaz.com/php/zend-framework-tips-and-tricks#comments</comments>
		<pubDate>Fri, 29 Jan 2010 19:38:45 +0000</pubDate>
		<dc:creator>Juozas</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[globals]]></category>
		<category><![CDATA[include path]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[models]]></category>
		<category><![CDATA[request]]></category>
		<category><![CDATA[response]]></category>
		<category><![CDATA[session]]></category>
		<category><![CDATA[testability]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[views]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://dev.juokaz.com/?p=964</guid>
		<description><![CDATA[ It&#8217;s always good to use great tools, but you need to make sure that you use them correctly, not just trying to code &#8220;just for it to work&#8221;. For this reason I decided to write down my usual list of things I mention when taking over some legacy project or just consulting someone how [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-460" title="Zend Framework" src="http://dev.juokaz.com/wp-content/uploads/2009/04/logo-zend-framework.jpg" alt="Zend Framework" width="169" height="114" /> It&#8217;s always good to use great tools, but you need to make sure that you use them correctly, not just trying to code &#8220;just for it to work&#8221;. For this reason I decided to write down my usual list of things I mention when taking over some legacy project or just consulting someone how to start.</p>
<p>Most of the outlined problems and solutions are focused on testability, maintainability and other good code practices. If you are not familiar with them, I recommend read about them ASAP as there is big chance that you are doing those things described in this post and don&#8217;t even realize how wrong they are. Believe me, you will soon find yourself a way better developer.</p>
<h5>Separate logic</h5>
<p>This one is the most obvious one, but trust me, I have found cases of it in every single project I have worked before (more than 10 with Zend Framework in a past half year and counting). If it&#8217;s controller, don&#8217;t do business logic, if it&#8217;s model don&#8217;t base behavior on POST parameters etc. Same applies to forms, bootstrap, views, various helpers and many more other components &#8211; logic should be separate and have its place. </p>
<p>Move all logic from controller to a model or <a href="http://dev.juokaz.com/programming/service-layer-in-web-applications">service</a>. Use forms only to handle validation and filtering, not to actually process data and persist it in any fashion. Hide session and authentication handling in one place and provide API for other algorithms. I can go on, but I hope it&#8217;s starting to get pretty clear, or at least it will eventually when you start testing your code: when you need to setup frontController, request, cookie and mail server just to test a form you realize that something is really wrong.</p>
<h5>Globals</h5>
<p>If you haven&#8217;t seen <a href="http://www.youtube.com/watch?v=-FRm3VPhseI">this</a> video, please do it immediately &#8211; you won&#8217;t regret it. Global state makes testing problematic and is completely opposite to what OOP proposes. This applies for use of <em>$_SERVER, $_SESSION</em> etc. values and all of them are accessible via request object (look at <em>Zend_Controller_Request_Http</em>) methods or separate classes, like Zend_Session. </p>
<p>Yet again I&#8217;m going to mention testability, because that&#8217;s something you always need to keep in mind. Test should not modify global variables, but rather inject mocked request/other objects which just return expected values (like client IP), because Zend Framework does pretty good job abstracting access to all global variables. </p>
<h5>Use form values, not request</h5>
<p>This one is both security and ease of coding issue, let&#8217;s look at this code sample:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$form</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Form<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_request<span style="color: #339933;">-&gt;</span><span style="color: #004000;">isPost</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$form</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">isValid</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_request<span style="color: #339933;">-&gt;</span><span style="color: #004000;">getPost</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$model</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Model<span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_request<span style="color: #339933;">-&gt;</span><span style="color: #004000;">getPost</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$model</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">save</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #b1b100;">else</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$form</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">populate</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_request<span style="color: #339933;">-&gt;</span><span style="color: #004000;">getPost</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>After form is validated (and hence values are filtered), raw values from request are still used from <em>$this->_request->getPost()</em>. Not only do you lose <em>Zend_Form</em> functions like ignored elements (for submit buttons for example) but also none of the filters are applied (which you use, yes?). Also I can pass pretty much anything I want and model needs to do way more validation. Hence <em>$form->getValues()</em> should always be used as it returns form data with respect to all defined rules and filters.</p>
<p>Form <em>populate()</em> method is also very overused. This method is designed to set default values for a form, from for example GB entry (when editing something) apart from that, you simply don&#8217;t need to use it as method <em>isValid()</em> sets values for all elements, so there is no need to apply default values too.</p>
<h5>Do not rely or use exit()/die()</h5>
<p>One of the first things I do is remove all these <em>exit()</em> calls and handle such cases with exceptions or <em>return</em> statements. There is only very very limited amount of situations where you actually need to use one of those functions. Just for example, imagine this controller action code:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">userHasPermissions</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_redirect<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'/'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000088;">$form</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Form_Add<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #666666; font-style: italic;">//submit form)</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// save with $form-&gt;getValues();</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span>_redirect<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'/index'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #990000;">exit</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// do something else</span></pre></div></div>

<p>First problem &#8211; thinking that <em>$this->_redirect()</em> will call <em>exit()</em> and hence nothing else will be executed. Even though this is true by default, this should be avoided in all cases. Not only it makes all <em>post*</em> events to not be fired, but also it makes testing impossible or incorrect. <em>Zend_Test</em> disables use of <em>exit()</em> in controller helpers, so in this case while testing you cannot test permissions checking as in all cases it will still execute later code. To fix this just add <em>return</em> in front of redirect (<em>return $this->_redirect(&#8216;/&#8217;)</em>) and you are safe.</p>
<p>Furthermore, second <em>exit()</em> is completely useless and makes code even more untestable. Again you can just use <em>return</em> to cancel later code (view will not be rendered as <em>viewRenderer</em> helper checks for redirection header and does nothing if detects such). From my experience, after saving entry, there is only some assignments to view in left code so you won&#8217;t suffer a lot if you just leave redirect, of course without <em>exit()</em>.</p>
<h5>Use a framework, not PHP</h5>
<p>This can sound wrong at first, but if you use a framework (Zend Framework in this case) don&#8217;t start throwing in hacks from 5 year old PHP apps. Like this (controller action):</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$object</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Some_Object<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$image</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$object</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">generateImage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">header</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Content-type: image/jpeg'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$image</span><span style="color: #339933;">;</span></pre></div></div>

<p>I don&#8217;t even know where to start&#8230; All this logic is incorporated in response object, so you can do things like:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getResponse</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setHeader</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Content-type&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'image/jpeg'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getResponse</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setBody</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$image</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>It might seem as same thing, but it&#8217;s not. Yet again you can actually test it, you are not working with global state (<em>header()</em> is global state function) and request dispatch process is left working as it should. Controllers do not output any data (hence no echo should be used) they just get request object and return response object, that&#8217;s it. In a similar fashion as <em>exit()</em> breaks dispatch process, outputting from controller does that too, so don&#8217;t forget to make sure that you preserve <a href="http://dev.juokaz.com/wp-content/uploads/2009/12/sequence_globale.jpg">this flow</a>.</p>
<h5>Some small ones</h5>
<p><em>Application.ini</em> has a property <em>includePaths</em>, which is used to add additional paths to include path. Even though it works great, I still recommend not to use it because it will add those paths every time you create new application instance (true for 1.9, can change in future). If you try to do some controllers testing, you are probably going to instantiate it before every single test and after some hundreds of tests you will notice that somehow it&#8217;s getting slower and slower. That took me a few hours to find, though fix was easy, but still keep that in mind.</p>
<p>If you are using <a href="http://jquery.org">jQuery</a> or any other javascript view helpers, take full power of them. By that I mean use functions like <em>addJavascriptFile()</em>, <em>addJavascript()</em>, <em>addStylesheet()</em>, <em>addOnload()</em> etc. to add some additional resources and code from views. If you add javascript straight to view everything will still work, but by using view helper container you will have all your code nicely placed in one place and not scattered all other the place. </p>
<h5>Conclusion</h5>
<p>This is just a small list of problems and issue I have seen in my work &#8211; there are way more to look at (you can share some tips too). I hope those will give you some idea how to work with Zend Framework in a clean fashion and you will soon find that your code is starting to look nicer and coding time is decreasing as everything is nicely separated and transparent to other code. </p>
]]></content:encoded>
			<wfw:commentRss>http://dev.juokaz.com/php/zend-framework-tips-and-tricks/feed</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Why Zend Framework?</title>
		<link>http://dev.juokaz.com/php/why-zend-framework</link>
		<comments>http://dev.juokaz.com/php/why-zend-framework#comments</comments>
		<pubDate>Mon, 07 Dec 2009 21:01:18 +0000</pubDate>
		<dc:creator>Juozas</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[cla]]></category>
		<category><![CDATA[comparison]]></category>
		<category><![CDATA[consulting]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[scaffolding]]></category>
		<category><![CDATA[symfony]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://dev.juokaz.com/?p=937</guid>
		<description><![CDATA[ As you might have noticed I mostly write about Zend Framework and related content. This has a lot of underlying reasons, so I decided to wrap up my thoughts about it and why to (not)use Zend Framework for your own projects. This is not a comparison of frameworks though, because I don&#8217;t feel like [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-460" title="Zend Framework" src="http://dev.juokaz.com/wp-content/uploads/2009/04/logo-zend-framework.jpg" alt="Zend Framework" width="169" height="114" /> As you might have noticed I mostly write about <a href="http://framework.zend.com/">Zend Framework</a> and related content. This has a lot of underlying reasons, so I decided to wrap up my thoughts about it and why to (not)use Zend Framework for your own projects. This is not a comparison of frameworks though, because I don&#8217;t feel like having enough experiences with other frameworks to make a fare comparison, that&#8217;s why this is going to be only a Zend Framework analysis. </p>
<h5>History</h5>
<p>First time I have actually built an application with <a href="http://dev.juokaz.com/tag/zend-framework">Zend Framework</a> was about a half year ago, if I remember correctly version 1.8 was already around. Although my first applications were more than two years ago, but hey were more than tests and playing with at that time new features. So as I said above, not that long ago I switched most of my company&#8217;s code to use Zend Framework, contributed some code and have also started working as Zend Framework consultant (drop me an email if interested), so I think I have a pretty decent experience to judge it.</p>
<p>Before diving in to the analysis, I would like to clarify, that the reasons why I&#8217;m not using other frameworks are mainly caused by the fact that I didn&#8217;t had a chance to do that. Since I&#8217;m usually working with projects lasting more than 3 months, I need to be confident enough to know that after 2 months I don&#8217;t need to throw everything away and start from scratch. Also to test a framework for me is not to create a <a href="http://en.wikipedia.org/wiki/Hello_world_program">Hello World application</a>, I need to build something serious to know what features are missing and what problems can be a big issue. Nevertheless, I&#8217;m planning to do some research sometime.</p>
<h5>Advantages</h5>
<p>For me the most important piece of software: how <strong>customizable</strong> it is. As you might have noticed from the posts like <a href="dev.juokaz.com/programming/service-layer-in-web-applications">this</a>, I usually work with complex web application and would like to have ability to built it from ground up. Zend Framework was perfect for this, because everything is just a collection of building blocks, literally (or <a href="http://en.wikipedia.org/wiki/Loose_coupling">loosely coupled</a> in proper terms). I really liked that there is no <em>default</em> or even worse required structure and everything can be configured very easily.</p>
<p>Because I&#8217;m also in a position responsible for a whole project, <strong>quality</strong> for me is very important. I don&#8217;t know how other frameworks handle this, but <a href="http://www.zend.com">Zend</a> is pretty serious with what&#8217;s in framework and how the code is maintained. Starting from requirement to sign Contributor License agreement (known as <a href="http://framework.zend.com/wiki/display/ZFPROP/Contributor+License+Agreement">CLA</a>) and requirement of 80% unit-tests coverage, ending with <a href="http://devzone.zend.com/article/10049">bug hunt days</a>. Somehow it helps me to have a confidence to rely on the framework, and backwards compatibility has never been an issue (it&#8217;s <a href="http://devzone.zend.com/article/11364-DevZone-updated-to-Zend-Framework-v1.9.5">surprisingly good</a>).</p>
<p><a href="http://dev.juokaz.com/wp-content/uploads/2009/12/zend2.gif"><img class="alignnone size-medium wp-image-950" title="Zend Framework components" src="http://dev.juokaz.com/wp-content/uploads/2009/12/zend2-300x219.gif" alt="Zend Framework components" width="210" height="153" /></a><strong>Variety of components</strong> and libraries makes development faster because I do not need to search for another library (there is also coding standards problem and a lot of smaller libraries are just a bunch of files, without any clear structure). As of today, I probably have used more than 90% of available components and because they tend to share the same configuration style or just work style, it didn&#8217;t took long to start using them. For example, just last night I converted whole application to use custom routes (one custom route per action) in about 4 hours, without having done it before at all.</p>
<p><strong>Community</strong> is number one best thing of Zend Framework. Apart from contributors, there are thousands of people willing to help and share their knowledge. Usually I hangout in twitter (<a href="http://www.twitter.com/juokaz">here</a>), but there are also IRC channels, mailing lists, forums and many more. I&#8217;m subscribed to hundreds of PHP blogs and from what I can see, Zend Framework articles are most common and usually in a very good quality. For me web applications development is not just writing code, so having a wonderful community really helps.</p>
<h5>Disadvantages</h5>
<p><a href="http://dev.juokaz.com/wp-content/uploads/2009/12/sequence_globale.jpg"><img class="alignnone size-medium wp-image-943" style="float: right; margin-left: 5px;" title="Zend Framework dispatch" src="http://dev.juokaz.com/wp-content/uploads/2009/12/sequence_globale-300x201.jpg" alt="Zend Framework dispatch" width="210" height="141" /></a><strong>Hard to learn</strong>. This is not a problem (any more) for me, but can be tricky when working with others, especially with things like form decorators. Even though Zend Framework has a very good <a href="http://framework.zend.com/manual/en/zend.form.elements.html#zend.form.elements.decorators">documentation</a>, I would say, that used techniques are sometimes not straightforward for starters and can lead to a very bad code. As with example with form decorators, once you <em>get</em> them, work with forms will be a joy, however at first they seem as pointless complication. I guess the best thing is just read the manual properly (<a href="http://en.wikipedia.org/wiki/RTFM">RTFM</a> in more rude words) &#8211; you will benefit later.</p>
<p>For some an issue can be that Zend Framework has <strong>no <a href="http://en.wikipedia.org/wiki/Scaffold_(programming)">scaffolding</a></strong>. In short, scaffolding is a user interface and logic generation based on database description and business logic definitions. If you have used frameworks like <a href="http://www.djangoproject.com/">Django</a> (my favorite for Python, has perfect <a href="http://docs.djangoproject.com/en/dev/intro/tutorial02/">scaffolding</a>), you will miss these things and it can be a first &#8220;brick wall&#8221; for your learning. Zend Framework has <a href="http://framework.zend.com/manual/en/zend.tool.project.html">Zend_Tool</a> component which provides basic project generation (you can customize it easily), but this is pretty much everything.</p>
<p>Connected to the both issues outlined above, Zend Framework in general is sometimes <strong>too much loosely coupled</strong>. Because all the components are just separate classes and out of the box you don&#8217;t get any sort of web application, one might have problems trying to understand what to do with all this <em>stuff</em> at all. It&#8217;s a great feature for me, but for someone not having any experience with Zend Framework it is probably impossible to build application without a help of blogs, books or (my recommendation) manual.</p>
<p>As you might have guessed, the fact that Zend Framework has lots of components also means that there should be enough developers to support them. However, this is not always the case and some components are really <strong>lacking new features or updates</strong>. For example <a href="http://framework.zend.com/manual/en/zend.pdf.html">Zend_Pdf</a> is quite out-dated and not moving as fast as a lot of us would like to. But hey, it&#8217;s an open-source framework, so if you have ideas of how to improve things &#8211; you are free to do, believe <a href="http://framework.zend.com/wiki/display/ZFPROP/Zend_Db_Adapter_Sqlsrv+-+Juozas+Kaziukenas+and+Rob+Allen">me</a>, it&#8217;s a great fun to contribute to such a influential software application. Nevertheless, always evaluate available components and choose what&#8217;s best for your project.</p>
<p>There is also the funny part &#8211; misconceptions and myths. I&#8217;ve just started working on a new article about these, so expect some interesting things very soon.</p>
<h5>Conclusion</h5>
<p>I hope it&#8217;s clear, that most of the advantages and disadvantages are coming from the same root &#8211; depending on what experience you have and what you are looking for Zend Framework can be a good or absolutely awful choice. For me it&#8217;s a perfect tool and currently I have no plans (even though <a href="http://www.symfony-project.org/">Symfony</a> is in my todo list) to use something else, and if you look at things which are coming in version 2.0 of both Doctrine and Zend Framework (yes, they will have integration)&#8230; Simply a good solution for serious work.</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.juokaz.com/php/why-zend-framework/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Zend Framework and Doctrine. Part 3</title>
		<link>http://dev.juokaz.com/php/zend-framework-and-doctrine-part-3</link>
		<comments>http://dev.juokaz.com/php/zend-framework-and-doctrine-part-3#comments</comments>
		<pubDate>Mon, 30 Nov 2009 11:57:53 +0000</pubDate>
		<dc:creator>Juozas</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[cache]]></category>
		<category><![CDATA[doctrine]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[optimization]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[speed]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://dev.juokaz.com/?p=909</guid>
		<description><![CDATA[ During last two months I spent massive amount of time tweaking Doctrine ORM framework and making it to perform as fast as possible (as you might have noticed from my never ending tweets). This post is devoted to performance and efficiency, with practical tips &#038; tricks how to reduce memory usage, make it work [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://dev.juokaz.com/wp-content/uploads/2009/11/doctrine-orm-php5.png" alt="doctrine-orm-php5" title="doctrine-orm-php5" width="191" height="53" class="alignnone size-full wp-image-847" style="margin-right: 5px;" /> During last two months I spent massive amount of time tweaking Doctrine ORM framework and making it to perform as fast as possible (as you might have noticed from my never ending <a href="http://twitter.com/juokaz">tweets</a>). This post is devoted to performance and efficiency, with practical tips &#038; tricks how to reduce memory usage, make it work faster and save resources.</p>
<p>Doctrine is a very powerful framework, however you should study its behavior a little bit to get it working properly. As it turns out &#8211; it&#8217;s not that hard. </p>
<h5>Speed</h5>
<p>One of the first things I recommend looking at is <a href="http://www.doctrine-project.org/documentation/manual/1_2/en/caching:query-cache-&#038;-result-cache">query cache</a>. Because there is quite a lot happening in turning <a href="http://www.doctrine-project.org/documentation/manual/1_2/nl/dql-doctrine-query-language">DQL</a> statement into the SQL query, <strong>caching</strong> that process can increase performance by a big margin. Best choice &#8211; <a href="http://en.wikipedia.org/wiki/PHP_accelerator">APC</a>, although robo47.net has an <a href="http://www.robo47.net/codeschnipsel/32-Adapter-fuer-Doctrine_Cache-zu-Zend_Cache">example</a> code for use of Zend_Cache adapters, just don&#8217;t forget that file back-end is probably not the best pick.</p>
<p><strong>Hydrators</strong> are probably the easiest thing to misuse. Hydration in Doctrine language is turning SQL query results into data graph. It can be an array, object or single value. It&#8217;s very nice to get results as PHP objects (in this case &#8211; models), however it&#8217;s slow. Slower than hydrating like array, and much slower than getting raw result from <a href="http://uk2.php.net/manual/en/book.pdo.php">PDO</a>. That&#8217;s why I always recommend answering one simple question: &#8220;will you be updating/deleting records?&#8221;. If the answer is no &#8211; hydrate as array, because you are not going to need an actual model (usually).</p>
<p>For this reason I always try to use array notation to access properties rather than like-object-vars one. Basically instead of <em>$product->name</em> I tend to write <em>$product['name']</em>, which returns the same result, but makes <strong>switching to array hydration very easy</strong>. You can find more tips and tricks at Doctrine manual <a href="http://www.doctrine-project.org/documentation/manual/1_2/en/data-hydrators">here</a>, but the key moment is to remember that the faster data structure in PHP is array (I believe so), so if application is not performing well &#8211; start playing with hydrations first.</p>
<p>Doctrine has a very nice support for relations, where they work like proxies and data can be retrieved when it&#8217;s needed (lazy-loading). However, this is wrong:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> Doctrine_Core<span style="color: #339933;">::</span><span style="color: #004000;">getTable</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'User'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">find</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">Comments</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$comment</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
   <span style="color: #b1b100;">print</span> <span style="color: #000088;">$comment</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">NewsItem</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This code is bad, because for each <em>comment</em> you will load <em>news item</em> using a <strong>separate query</strong>, hence you are wasting db server resources and making code slower. Optimization is pretty straightforward:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$query</span> <span style="color: #339933;">=</span> Doctrine_Query<span style="color: #339933;">::</span><span style="color: #004000;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$query</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">from</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Comments C'</span><span style="color: #009900;">&#41;</span>
        <span style="color: #339933;">-&gt;</span><span style="color: #004000;">innerJoin</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'C.NewsItem N'</span><span style="color: #009900;">&#41;</span>
        <span style="color: #339933;">-&gt;</span><span style="color: #004000;">where</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'C.user_id = ?'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$query</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">execute</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$comment</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
   <span style="color: #b1b100;">print</span> <span style="color: #000088;">$comment</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">NewsItem</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Here all the data is loaded in <strong>one query</strong> and everything happens much faster (and in this case making it to hydrate as array would also improve the performance).</p>
<p>However, make sure you <strong>know what you are joining</strong>. For example imagine that in previous example <em>news item</em> is also one-to-many (comment has many news items) relation and user <em>1</em> has written 1000 comments where each comment is attached to average <em>news items</em>. Query above will return 50&#8242;000 records (<a href="http://en.wikipedia.org/wiki/Cross_product">50 * 1000</a>) which Doctrine will need to hydrate then. This will be very slow and probably going to kill your web server after some time. One day I had a query which was returning 2GB of data, server admins where probably not very happy about it&#8230;</p>
<h5>Memory</h5>
<p>One of my favorite parts of software development is playing with memory usage and making it efficient. Even though it sounds really simple, debugging it and finding it where the memory is <a href="http://en.wikipedia.org/wiki/Memory_leak">leaking</a> is not an easy task. Recently I was using Doctrine to work with quite big datasets (on average 50&#8242;000 of records) and probably have tried all the possible tricks to make Doctrine memory efficient. My code looked really simple:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$data</span> <span style="color: #339933;">=</span> Doctrine_Query<span style="color: #339933;">::</span><span style="color: #004000;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">execute</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$data</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$item</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// do some work here</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>You might expect that memory usage would be steady, however it is not. Doctrine uses <a href="http://martinfowler.com/eaaCatalog/identityMap.html">identity map</a> and objects also have a lot of references which makes <strong>freeing up memory</strong> a tricky job. As my experience showed, even though records have a method <em>free()</em> which is supposed to de-reference it, sometimes it doesn&#8217;t help.</p>
<p>So to make memory management work, make sure to try these:</p>
<ul>
<li><strong>$record->free(true)</strong> &#8211; deep free-up, calls <em>free()</em> on all relations too</li>
<li><strong>$collection->free()</strong> &#8211; free all collection references</li>
<li><strong>Doctrine_Manager::connection()->clean()</strong> &#8211; cleanup connection (and remove identity map entries)</li>
</ul>
<p>With some debugging and profiling (and these methods) you hopefully can make memory usage to be low. I&#8217;m also using some custom iterators (available <a href="http://github.com/juokaz/php-examples/tree/master/doctrine-iterators/">here</a>) to <strong>divide query into chunks</strong>, because loading 50&#8242;000 of objects in one go is not going to work, so you might want to look at it too. </p>
<p>Another recommended tip: make sure to <strong>free queries</strong> too. As collections hold references to all records, query object also has some references to parsed sub-parts of query. For this I use auto-free setting enabled by (available in my first part post also <a href="http://dev.juokaz.com/php/zend-framework-and-doctrine-part-1">here</a>):</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// enable automatic queries resource freeing</span>
<span style="color: #000088;">$manager</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setAttribute</span><span style="color: #009900;">&#40;</span>
	Doctrine_Core<span style="color: #339933;">::</span><span style="color: #004000;">ATTR_AUTO_FREE_QUERY_OBJECTS</span><span style="color: #339933;">,</span>
	<span style="color: #009900; font-weight: bold;">true</span>
<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>It&#8217;s very easy to forget to free a query and it&#8217;s again creating these references which makes <a href="http://php.net/manual/en/function.gc-enable.php">garbage collector</a>&#8217;s work hard. Nevertheless, after enabling this one I don&#8217;t know any other place where the memory can start to leak.</p>
<p>Last step &#8211; <strong>PHP 5.3</strong>. I&#8217;ve been working with this version for a few months and it works great, so if it&#8217;s possible &#8211; I recommend using it (you will also help with testing frameworks, but both Zend Framework and Doctrine already should work fine). One important function here is <a href="http://php.net/releases/5_3_0.php">improved</a> garbage collector, so the actual script takes less memory to execute. I haven&#8217;t recorded benchmarks on this one, but what I&#8217;ve noticed during development is that 5.3 does in fact has a lower peak memory usage. </p>
<h5>Conclusion</h5>
<p>I think I haven&#8217;t missed anything here, or at least these are the tips which made applications work fast (if I have &#8211; let me know). To finish with &#8211; good optimizations are done by comprehensive benchmarking and profiling, so the fact that Doctrine is a big framework doesn&#8217;t necessary mean it&#8217;s slow too. At the end of the day, it&#8217;s usually only a matter of reading a manual. </p>
<p><strong>All parts</strong>:</p>
<ol>
<li><a href="http://dev.juokaz.com/php/zend-framework-and-doctrine-part-1">Zend Framework and Doctrine. Part 1</a></li>
<li><a href="http://dev.juokaz.com/php/zend-framework-and-doctrine-part-2">Zend Framework and Doctrine. Part 2</a></li>
<li><a href="http://dev.juokaz.com/php/zend-framework-and-doctrine-part-3">Zend Framework and Doctrine. Part 3</a></li>
</ol>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.juokaz.com/php/zend-framework-and-doctrine-part-3/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Service Layer in Web applications</title>
		<link>http://dev.juokaz.com/programming/service-layer-in-web-applications</link>
		<comments>http://dev.juokaz.com/programming/service-layer-in-web-applications#comments</comments>
		<pubDate>Thu, 26 Nov 2009 16:53:47 +0000</pubDate>
		<dc:creator>Juozas</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[acl]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[dao]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[doctrine]]></category>
		<category><![CDATA[matthew]]></category>
		<category><![CDATA[models]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[permissions]]></category>
		<category><![CDATA[saas]]></category>
		<category><![CDATA[users]]></category>
		<category><![CDATA[zend framework]]></category>
		<category><![CDATA[zf]]></category>

		<guid isPermaLink="false">http://dev.juokaz.com/?p=888</guid>
		<description><![CDATA[In my professional live I mostly work with enterprise web applications which are quite demanding for big layer of business logic (that&#8217;s another article I guess) and decoupling of application layers. During this year I invested quite a lot for a search of a good ways to architecture a big application and make it simply [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://dev.juokaz.com/wp-content/uploads/2009/11/ServiceLayerSketch.gif"><img class="alignnone size-full wp-image-889" title="Service layer sketch" src="http://dev.juokaz.com/wp-content/uploads/2009/11/ServiceLayerSketch.gif" alt="Service Layer Sketch" width="199" height="229" style="float: right;" /></a>In my professional live I mostly work with enterprise web applications which are quite demanding for big layer of business logic (that&#8217;s another article I guess) and decoupling of application layers. During this year I invested quite a lot for a search of a good ways to architecture a big application and make it simply good. Quite a while ago <a href="http://weierophinney.net/matthew/">Matthew Weier O&#8217;Phinney</a> introduced service layer in one of his great talks about models, since then service layer become one of the key architectural component one my applications. Here I&#8217;m going to show a few examples and use cases where it&#8217;s very useful. </p>
<h5>&#8220;Old-style&#8221; interaction with data</h5>
<p>I&#8217;ve used it for different projects, but one of the best examples of how great this concept is <a href="http://en.wikipedia.org/wiki/Software_as_a_service">SaaS</a> or any other users-based application. Some years ago I used to have code which worked like this (let&#8217;s say this is controller action):</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> userInfo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
     <span style="color: #000088;">$userDao</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Users<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$userDao</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getUser</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'id'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>And then in my database access class <em>Users</em> I just execute sql query with a given user id. However, after some thinking I looked at it again and though &#8211; why does controller need to know the userId? I mean, of course it&#8217;s a job of controller to process requests and control application flow, but logically &#8211; if an action is named <em>userInfo</em> and we got to the point where we need the user info (hence the user is authenticated and validated) why do we need to pass user id? It&#8217;s clear that some part of code already knows it.</p>
<p>One more case: if a site is a e-commerce it&#8217;s clear that user has only access to his orders, addresses information etc. but in a <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">basic MVC</a> you either fetch by <em>Id</em> and then check if it&#8217;s in fact user&#8217;s order or create a method like in a first example. Again, not very clear and not easy to maintain. There are more problems too: by passing user id and id of a record you assume that controller knows that this is a key to get the information. But it&#8217;s wrong &#8211; business layer knows that user has orders; controller only knows that there is such a thing like orders and it can be retrieved by id. <a href="http://www.mikebernat.com/blog/MVC_-_Fat_Models_and_Skinny_Controllers_">That&#8217;s it</a>.</p>
<h5>Service layer</h5>
<p>For such things I use service layer: it has user info injected from bootstrap (or directly to a constructor) and operates with data only accessible to the user. So previous method becomes to:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> userInfo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
     <span style="color: #000088;">$service</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> UsersService<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$service</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getUser</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>of course you would have a separate method to fetch other users data, but for sake of simplicity let&#8217;s just say that this method returns some private info (like address for example). Here my action is completely unaware of what user id actually is &#8211; it expects a user object, it gets it. Very simple, very clean and very easy to maintain. </p>
<p>Getting back to the e-commerce example, action for a view order would look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> viewOrder<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
     <span style="color: #000088;">$service</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> OrdersService<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #000088;">$order</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$service</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getOrder</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'id'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Again &#8211; this controller action doesn&#8217;t care what user id is in current session, it just gets an order by its id. If this action returns false (or throws exception with error type) then it means order cannot be retrieved, or in other words &#8211; service cannot return id by given id. It can be permissions problem, it can be something else &#8211; but controller is completely freed from checking all this unnecessary things.</p>
<h5>Practical usage</h5>
<p>As you might have noticed, service layer is intermediate layer between models and controllers &#8211; in the same way as you would use Flickr or <a href="http://code.google.com/apis/youtube/overview.html">Youtube API</a> to work with remote data, you use service layer API to work with application resources. All the business logic resides in service layer, where also using other service layer, models are retrieved, changed, saved, returned etc. Controller has zero lines which contain a word <em>Doctrine</em> (or any other database layer class). None.</p>
<p><img src="http://dev.juokaz.com/wp-content/uploads/2009/11/soa-additional-service-layer.jpg" alt="Service layer " title="Service layer " width="450" height="322" class="alignnone size-full wp-image-905" /></p>
<p>Another advantage of using a service layer &#8211; it&#8217;s a good place to merge information sources. I think it&#8217;s more like a style of mine, but I tend to have models very clean &#8211; only with logic on that model. This is mainly because I usually use <a href="http://dev.juokaz.com/tag/doctrine">Doctrine</a> models and I don&#8217;t want to put anything in them. For example just yesterday Adam from <em>jazzslider.org</em> posted a very good article about <a href="http://www.phpquebec.org/modules/news/article.php?storyid=103">using Acl with models</a> by creating custom listeners. With all respect, even though it works really great, I don&#8217;t think it&#8217;s a clean approach &#8211; I see models and permissions control as separate layers.</p>
<p>Furthermore, having this layer makes replacing database layer (or even models layer) a little bit easier &#8211; because all the other code communicates with data using given <a href="http://en.wikipedia.org/wiki/Application_programming_interface">API</a> (from service layer) so as long as results returned are the same, they don&#8217;t care how they are actually retrieved (for example they can come from cache, text file or created on-the-fly). But if you would have <a href="http://framework.zend.com/manual/en/zend.db.select.html">Zend_Db_Select</a> calls all other the place, migrating to Doctrine&#8217;s <a href="http://www.doctrine-project.org/documentation/manual/1_0/en/dql-doctrine-query-language">DQL</a> can be a pain. From my personal experience, I successfully migrated my own ORM code with about 50 models to Doctrine in about 4 days without changing a line in controllers (also because of tests I had).</p>
<p>To be honest, I&#8217;ve only tried various service layer implementations with <a href="http://framework.zend.com/">Zend Framework</a>. Even a default autoloader has a resource namespace <em>Service_</em> with <em>services</em> folder inside application, so I didn&#8217;t need to do any hacking to get it working. Nevertheless, this pattern doesn&#8217;t require any specific framework futures, but if a framework has good dependency injector (like <a href="http://components.symfony-project.org/dependency-injection/">this</a> one from Symfony) it can make things even cleaner. </p>
<h5>Conclusion</h5>
<p>I don&#8217;t know if I have convinced you to look at this pattern, but I definitely recommend looking at it. Especially when your application gets quite big and you need some sort of functionality to work with all these models (on average, I used service layer with applications having roughly 80 models). Nevertheless, there are tons of different ways to do this, so I definitely recommend reading a book by M. Fowler called <a href="http://martinfowler.com/eaaCatalog/">&#8220;Patterns of Enterprise Application Architecture (P of EAA)&#8221;</a>. One of the best sources for enterprise applications I&#8217;ve read so far.</p>
<p><em><sup>*</sup> Image copyright: <a href="http://martinfowler.com/eaaCatalog/serviceLayer.html">http://martinfowler.com/eaaCatalog/serviceLayer.html</a> and <a href="http://www.tutorialspoint.com/images/soa-additional-service-layer.jpg">http://www.tutorialspoint.com/images/soa-additional-service-layer.jpg</a></em></p>
]]></content:encoded>
			<wfw:commentRss>http://dev.juokaz.com/programming/service-layer-in-web-applications/feed</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>Zend Framework and Doctrine. Part 2</title>
		<link>http://dev.juokaz.com/php/zend-framework-and-doctrine-part-2</link>
		<comments>http://dev.juokaz.com/php/zend-framework-and-doctrine-part-2#comments</comments>
		<pubDate>Wed, 18 Nov 2009 10:05:32 +0000</pubDate>
		<dc:creator>Juozas</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[application.ini]]></category>
		<category><![CDATA[cli]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[doctrine]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[models]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://dev.juokaz.com/?p=866</guid>
		<description><![CDATA[Today we start actual development with Doctrine and Zend Framework. Base of this post is my code which I have been using for quite a few projects and it worked really well.
These are the steps required to setup Doctrine:

Create MySQL (or any other adapter supported by Doctrine) database
Download Doctrine 1.2 (as of today &#8211; 1.2.0beta3). [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://dev.juokaz.com/wp-content/uploads/2009/11/doctrine-orm-php5.png" alt="doctrine-orm-php5" title="doctrine-orm-php5" width="191" height="53" class="size-full wp-image-847" style="float: left; margin-right: 5px;" />Today we start actual development with Doctrine and Zend Framework. Base of this post is my code which I have been using for quite a few projects and it worked really well.</p>
<p>These are the steps required to setup Doctrine:</p>
<ol>
<li>Create MySQL (or any other adapter <a href="http://www.doctrine-project.org/documentation/manual/1_2/en/introduction-to-connections">supported</a> by Doctrine) database</li>
<li>Download Doctrine 1.2 (as of today &#8211; <a href="http://www.doctrine-project.org/download/1_2_0_BETA3/format/tgz/package/">1.2.0beta3</a>). Believe, it&#8217;s stable enough (no problems at all for me) and supports functions all functions we are going to use later</li>
<li>Setup <em>application.ini</em> and <a href="http://framework.zend.com/manual/en/zend.application.quick-start.html#zend.application.quick-start.resources">application resource</a></li>
<li>Generate models from database</li>
<li>Profit!</li>
</ol>
<p>To start with, <strong>download</strong> this <a href="http://dev.juokaz.com/examples/doctrine/doctrine_v1.zip">archive</a> (or get updated version from my public <a href="http://github.com/juokaz/php-examples/tree/master/doctrine-application-resource/">repository</a>). It has everything you will need. Some of the files are quite long so I&#8217;m not going to post them here, it&#8217;s better that you download them and have them ready to be used as the article progresses. </p>
<h5>Create MySQL database</h5>
<p>For MySQL databases I use a product called &#8220;<a href="http://dev.mysql.com/downloads/workbench/5.1.html">MySQL Workbench</a>&#8220;. If you haven&#8217;t tried it I definitely recommend to give it a go &#8211; it basically allows you create a database as a <a href="http://forge.mysql.com/w/images/a/a8/Mysql_workbench_tbl_editor.png">diagram</a> and then export it to sql file or update actual database (can be risky). Since I expect you to have enough knowledge how to create a database I won&#8217;t write anything more &#8211; you can find <a href="http://www.webpronews.com/topnews/2005/06/06/mysql-for-beginners-how-to-create-a-mysql-database">tutorials</a> all over the web.</p>
<h5>Download Doctrine</h5>
<p>After downloading Doctrine extract it to <em>library</em> folder. You should have <em>./library/Doctrine.php</em> in your library folder. Although, you can use <em>svn:externals</em> (if you are using SVN at all) to remove Doctrine code from repository, but in this case you probably need to setup paths in application resource file explain below to use Doctrine_Core if you just get Doctrine folder contents (from <a href="http://svn.doctrine-project.org/tags/1.2.0-BETA3/lib/Doctrine/">here</a>).</p>
<p>Most important point here &#8211; don&#8217;t forget to <a href="http://www.doctrine-project.org/download">download</a> <strong>1.2</strong>, not version 1.1. Even though it doesn&#8217;t have a stable release, 1.1 doesn&#8217;t support models generation as we want them to be (auto-loadable). Also this week all bugs have been fixed which I reported and now models generation works perfectly. From my personal experience, I haven&#8217;t even used 1.1 at all (started with 1.2 when it was in alpha) and didn&#8217;t had any problems, so my recommendation &#8211; use 1.2. </p>
<h5>Setup application.ini and application resource</h5>
<p>From the file listed above open a file called <em>application.ini</em>. Append you current configuration (more on getting Zend Framework project running can be found <a href="http://framework.zend.com/docs/quickstart/create-your-project">here</a>) with settings in that file (leave compiled and cache options to false for now). Doctrine uses DNS strings to connect to a database, there are quite a few <a href="http://www.doctrine-project.org/documentation/manual/1_2/en/introduction-to-connections#dsn,-the-data-source-name:examples">examples</a> in the documentation. If you have used <a href="http://php.net/manual/en/book.pdo.php">PDO</a> before you be very familiar.</p>
<p>In archive there is a file called <em>library/resource.php</em>. Depending on what namespace you use for outside-Zend code, paste it to chosen folder. If you choose to have &#8220;App&#8221; as a namespace, just copy that file to <em>library/App/Application/Resource/Doctrine.php</em>. And don&#8217;t forget to have:</p>

<div class="wp_syntax"><div class="code"><pre class="ini" style="font-family:monospace;">autoloaderNamespaces<span style="">&#91;</span><span style="">&#93;</span> <span style="color: #000066; font-weight:bold;">=</span> <span style="color: #933;">&quot;App_&quot;</span>
pluginpaths.App_Application_Resource <span style="color: #000066; font-weight:bold;">=</span> <span style="color: #933;">&quot;App/Application/Resource&quot;</span></pre></div></div>

<p>in <em>application.ini</em> also, otherwise library code won&#8217;t be auto-loaded. I don&#8217;t recommend putting any code in Zend folder, because it will create tons of problems in the future. Having App or ProjectName library folders allows to have your own code in separate packages which you can use in later projects (I usually have App, ProjectName, CompanyName). </p>
<p>Provided <em>application.ini</em> file isn&#8217;t that much configurable, mainly because it wasn&#8217;t supposed to be released at all. If you are looking for something more dynamic, look no further than this <a href="http://framework.zend.com/wiki/display/ZFPROP/Zend_Application_Resource_Doctrine+-+Matthew+Lurz">proposal</a> in Zend incubator. Nevertheless, my code should work fine &#8211; it has all options required to get you started and have been tweaked with settings which I found to be really useful. </p>
<h5>Generate models from database</h5>
<p>This part is the most awesome. To start, just copy and paste everything from <em>scripts</em> folder in the zip archive to your scripts folder in application (I have scripts folder in the same level as application and library, in the root of project). There actually only two files &#8211; <em>doctrine-cli.php</em> and custom task in <em>Doctrine/Task/GenerateModels.php</em>. You can run doctrine-cli.php like this:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">php doctrine-cli.php</pre></div></div>

<p>and you should get a list of <a href="http://www.doctrine-project.org/documentation/manual/1_2/en/utilities#command-line-interface">all the possible tasks</a> (if you setup everything properly). To run my custom task, append &#8220;generate-models&#8221; to the end of previous command to get:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">php doctrine-cli.php generate-models</pre></div></div>

<p>This task will load your database schema and create all classes (table, base model, model) required for models. Doctrine also supports generating models from <em><a href="http://en.wikipedia.org/wiki/YAML">yaml</a></em> configuration files, though I&#8217;ve never used it before, but configuration should be almost the same.</p>
<h5>It works</h5>
<p>To test the models you can look at the generate code or start coding you application (or even run <em><a href="http://www.doctrine-project.org/documentation/manual/1_2/en/dql-doctrine-query-language">dql</a></em> task from <em>doctrine-cli.php</em>). For example you can test simply like this (adjust by models you have):</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$product</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Model_Product<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$product</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'Product name'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$product</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">save</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">print_r</span><span style="color: #009900;">&#40;</span>Doctrine_Core<span style="color: #339933;">::</span><span style="color: #004000;">getTable</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Model_Product'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">findAll</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">toArray</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>If everything has been configured properly you shouldn&#8217;t get any errors and this code (put it in controller) should output array of your saved data. Because of the settings in application resource, save() method also runs <a href="http://www.doctrine-project.org/documentation/manual/1_2/en/data-validation">validation</a> so if you missed a field and it breaks a <em>not null</em> constrain, this code will throw a validator exception. </p>
<h5>What&#8217;s next?</h5>
<p>This article has enough information to get you started and almost all the code provided it left as simple as possible and open for further modifications. I hope that in coming months code for Doctrine and Zend Framework integration will be completed and you can use Doctrine without any outside code.</p>
<p>Since we have application running now we can dive into actual usage, testing and more advanced stuff. I have code for these also and will be posting more articles very soon, even though the best resource for Doctrine is <a href="http://www.doctrine-project.org/documentation/manual/1_2/en/introduction">documentation</a>. If you have any problems with this code just leave a comment here or find my on twitter (<a href="http://www.twitter.com/juokaz">here</a>) and I will try to explain more.</p>
<p><strong>All parts</strong>:</p>
<ol>
<li><a href="http://dev.juokaz.com/php/zend-framework-and-doctrine-part-1">Zend Framework and Doctrine. Part 1</a></li>
<li><a href="http://dev.juokaz.com/php/zend-framework-and-doctrine-part-2">Zend Framework and Doctrine. Part 2</a></li>
<li><a href="http://dev.juokaz.com/php/zend-framework-and-doctrine-part-3">Zend Framework and Doctrine. Part 3</a></li>
</ol>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.juokaz.com/php/zend-framework-and-doctrine-part-2/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Zend Framework and Doctrine. Part 1</title>
		<link>http://dev.juokaz.com/php/zend-framework-and-doctrine-part-1</link>
		<comments>http://dev.juokaz.com/php/zend-framework-and-doctrine-part-1#comments</comments>
		<pubDate>Mon, 16 Nov 2009 14:09:07 +0000</pubDate>
		<dc:creator>Juozas</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[doctrine]]></category>
		<category><![CDATA[domain model]]></category>
		<category><![CDATA[giorgio]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[symfony]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://dev.juokaz.com/?p=845</guid>
		<description><![CDATA[If you are following twitter (you can find me there also) or any other social network, you might have noticed that there is a huge interest in Doctrine and Zend Framework integration. Since I&#8217;ve been using these libraries for quite a while now, so I&#8217;m going to explain some best practices and ways you can [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://dev.juokaz.com/wp-content/uploads/2009/11/doctrine-orm-php5.png" alt="doctrine-orm-php5" title="doctrine-orm-php5" width="191" height="53" class="size-full wp-image-847" style="float: left; margin-right: 5px;" />If you are following twitter (you can find <a href="http://www.twitter.com/juokaz">me</a> there also) or any other social network, you might have noticed that there is a huge interest in Doctrine and Zend Framework integration. Since I&#8217;ve been using these libraries for quite a while now, so I&#8217;m going to explain some best practices and ways you can do that.</p>
<h5>History</h5>
<p>To start with, in my opinion, <a href="http://framework.zend.com/">Zend Framework</a> never had a proper M from <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a>. It was quite common to use <a href="http://framework.zend.com/manual/en/zend.db.table.html">Zend_Db_Table</a> as base models class, but it was simply not practical. When you start dealing with relations and hierarchical data types it starts to get really tricky, because simply Zend_Db_Table doesn&#8217;t provide an extensive enough functionality.</p>
<p>So half a year ago Zend Framework developers started to look for better solutions. Quite obvious one was to start implementing their own <a href="http://en.wikipedia.org/wiki/Domain_model">Domain</a> layer. You can find quite a few different implementations of that in <a href="http://www.google.co.uk/search?hl=en&amp;source=hp&amp;q=zend+framework+domain+model&amp;btnG=Google+Search&amp;meta=&amp;aq=1&amp;oq=zend+framework+domain+">blogosphere</a>, and I chose this path also. However, after quite some time of developing my own code I realized that it&#8217;s simply not a right thing to do &#8211; I&#8217;m expected to deliver a product and I was &#8220;wasting&#8221; way too much time tweaking, testing, extending etc. my domain model code.</p>
<p>So about 3-4 months ago I completely switched to <a href="http://www.doctrine-project.org/">Doctrine</a>. After evaluating possible solutions I decided to stay with Doctrine for a long time. I don&#8217;t know any other solution coming, I definitely don&#8217;t want (mainly because I don&#8217;t have time) to invest on creating my own library and Doctrine is simply awesome when you get used to it. After all this time I can say that it was a right call &#8211; Doctrine is on a way to being officially supported in Zend Framework (<a href="http://www.symfony-project.org/">Symfony</a> has it right now) and with Doctrine 2.0 (you can see a short presentation of its new features right <a href="http://www.slideshare.net/jwage/doctrine-2-enterprise-persistence-layer-for-php">here</a>) it will be just a perfect tools combination. I would very much agree with <a href="http://giorgiosironi.blogspot.com/2009/11/whats-going-on-with-php-object.html">Giorgio</a> that:</p>
<blockquote><p>Thus, Doctrine 2 is going to become <strong>the first production-ready Orm for php</strong> and to be favored with seamless integration in both <a href="http://framework.zend.com/">Zend Framework</a> and <a href="http://www.symfony-project.org/">Symfony</a>.</p></blockquote>
<h5>Benefits</h5>
<p><img src="http://dev.juokaz.com/wp-content/uploads/2009/04/logo-zend-framework.jpg" alt="Zend framework" title="Zend framework" width="141" height="95" class="size-full wp-image-460" style="float: right; margin-left: 5px;" /> Some time ago I was actually involved in making a decision of choosing Doctrine over other libraries (main Zend Framework components) as part of my work, so here I&#8217;m going to outline some points which made that decision easier. </p>
<p><strong>Relations</strong>. I keep repeating this term every time I speak about Doctrine (or ORM&#8217;s in general), but for me it&#8217;s a key factor in writing code fast. Quick example: let&#8217;s image that our application consists of Order which has a list of Items where Item is Product and price, quantity information. Code for this situation:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$order</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Order<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$item</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> OrderItem<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$item</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">Product</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$product</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// product object from somewhere</span>
<span style="color: #000088;">$item</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">quantity</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$item</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">price</span> <span style="color: #339933;">=</span> <span style="color:#800080;">9.99</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$order</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">Items</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$item</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$order</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">save</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This is how much code I need to write myself. I&#8217;m going to show more examples in the future posts, but because Doctrine is ORM (object relation mapper) all the hierarchical structure of your application data becomes very easy to work with.  </p>
<p>What is more, Doctrine can <strong>generate</strong> all the <strong>model classes</strong> by itself. Now that&#8217;s a treasure! Just specify database connection in the config file, open up a terminal and run:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">php doctrine-cli.php generate-models-db</pre></div></div>

<p>In a few seconds all schema information is retrieved from the actual database and all the classes are created. My biggest project so far with Doctrine was worth more than 10&#8242;000 lines of models code. I don&#8217;t know how to count the time it saved and despite a few minor bugs in Doctrine library it worked exactly as we wanted.</p>
<p>I can list things I like about it for hours probably, so I&#8217;m going to finish this list with the future I consider to be a very big time saver. This feature is dynamics of models: <strong>inheritance</strong> and <strong>behaviors</strong>. Inheritance makes your objects have different classes even though they could be a same table (with for example <a href="http://www.doctrine-project.org/documentation/manual/1_1/en/inheritance#column-aggregation">type_id</a>). All the work needed to handle the actual schema is done in background.</p>
<p>Behaviors work in the same way &#8211; one line of code and a model becomes physically undeletable (called <a href="http://www.doctrine-project.org/documentation/manual/1_1/en/behaviors#core-behaviors:softdelete">soft-delete</a>) or has a separate table to save revisions. Behaviors are very similar to decorators in Zend_Form for example &#8211; they are small classes which can be added to the main class to extend its functionality. So in the end your mode could have all sorts of different functionality depending on how you &#8220;decorate&#8221; it.</p>
<h5>What&#8217;s next?</h5>
<p>I only wrote a few examples how great Doctrine actually is today, but you can expect a lot more. Especially in Zend Framework code side: application.ini settings, application resource to setup auto-loading, script to generate Zend Framework compatible models, testing Doctrine models and much more. I&#8217;m also involved in a work group making Doctrine and Zend Framework integration possible so you can expect great things to come (first proposal <a href="http://framework.zend.com/wiki/display/ZFPROP/Doctrine+1+and+Zend_Tool+Integration+-+Benjamin+Eberlei">here</a>).</p>
<p><em>If you have been following me on twitter you might have noticed that I tweet a lot of interesting material on both Zend Framework, Doctrine and general PHP so I would recommend following me there or subscribing to the RSS </em><a href="http://dev.juokaz.com/feed"><em>feed</em></a><em>. I haven&#8217;t been writing for a while now, but I will try as hard as I can to change it and write much more frequently &#8211; during past months I tried a lot of cool stuff which I would love to talk about.</em></p>
<p><strong>All parts</strong>:</p>
<ol>
<li><a href="http://dev.juokaz.com/php/zend-framework-and-doctrine-part-1">Zend Framework and Doctrine. Part 1</a></li>
<li><a href="http://dev.juokaz.com/php/zend-framework-and-doctrine-part-2">Zend Framework and Doctrine. Part 2</a></li>
<li><a href="http://dev.juokaz.com/php/zend-framework-and-doctrine-part-3">Zend Framework and Doctrine. Part 3</a></li>
</ol>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.juokaz.com/php/zend-framework-and-doctrine-part-1/feed</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Lambda functions are coming to PHP</title>
		<link>http://dev.juokaz.com/php/lambda-function-coming-to-php</link>
		<comments>http://dev.juokaz.com/php/lambda-function-coming-to-php#comments</comments>
		<pubDate>Thu, 26 Mar 2009 19:56:34 +0000</pubDate>
		<dc:creator>Juozas</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[anonymous function]]></category>
		<category><![CDATA[closures]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[php 5.3]]></category>

		<guid isPermaLink="false">http://dev.juokaz.com/?p=434</guid>
		<description><![CDATA[Only some days ago PHP.net introduced 5.3.0RC1 version, but future features have been known for quite a while. Namespaces and lambda functions (+ closures) are most anticipated, because they&#8217;ll increase flexibility and good-looks of code a lot. Today I&#8217;m going to try to prove why lambda functions are so useful.
Because of &#8220;Functional Programming&#8221; course I [...]]]></description>
			<content:encoded><![CDATA[<p>Only some days ago PHP.net introduced <a href="http://www.php.net/archive/2009.php#id2009-03-24-1">5.3.0RC1</a> version, but future features have been known for quite a while. Namespaces and <a href="http://en.wikipedia.org/wiki/Lambda_function">lambda functions</a> (+ closures) are most anticipated, because they&#8217;ll increase flexibility and good-looks of code a lot. Today I&#8217;m going to try to prove why lambda functions are so useful.</p>
<p>Because of &#8220;Functional Programming&#8221; course I had in <a href="http://www.ed.ac.uk">university</a>, I love lambda functions. At first they seemed a little bit strange, but hey &#8211; in <a href="http://www.haskell.org/">Haskell</a> you write:</p>

<div class="wp_syntax"><div class="code"><pre class="haskell" style="font-family:monospace;">Input: <span style="font-weight: bold;">map</span> <span style="color: green;">&#40;</span>\x <span style="color: #339933; font-weight: bold;">=&gt;</span> x<span style="color: #339933; font-weight: bold;">*</span><span style="color: red;">3</span><span style="color: green;">&#41;</span> <span style="color: green;">&#91;</span><span style="color: red;">1</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: red;">2</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: red;">3</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: red;">4</span><span style="color: green;">&#93;</span>
Output: <span style="color: green;">&#91;</span><span style="color: red;">3</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: red;">6</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: red;">9</span><span style="color: #339933; font-weight: bold;">,</span><span style="color: red;">12</span><span style="color: green;">&#93;</span></pre></div></div>

<p>No need to create for loops (which doesn&#8217;t exists in Haskell at all) and code is much more flexible. Functional languages allows creating functions which accepts functions as arguments, not only integers or floats. That&#8217;s why most functions are very short, but are very easily connectable together. </p>
<p>I think one the best examples of lambda functions usefulness is sorting. Image this scenario: <em>$books</em> <a href="http://docs.php.net/manual/en/class.arrayobject.php">collection</a> holds books information and you need to sort it by title; author; publish year and author; publish city and title. How you are going to do it? It&#8217;s easy and you probably would write something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Sort by title</span>
<span style="color: #000088;">$books</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">sortByTitle</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'ASC'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// Sort by publisher year, author</span>
<span style="color: #000088;">$books</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">sortByPublishYear</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'DESC'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">sortByAuthor</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'ASC'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>However, it looks good and does work just fine, but it&#8217;s not very practical &#8211; you need to create functions for all keywords (title, author, publish year, etc.). You may argue, that __call() can be used and that&#8217;s absolutely true, but it&#8217;s even harder to maintain and code it, still usable though. </p>
<p>Nevertheless, 5.3 version of <a href="http://dev.juokaz.com/category/php">PHP</a> introduces lambda functions (also called <a href="http://docs.php.net/functions.anonymous">anonymous functions</a>), which can simplify your work a lot (I haven&#8217;t tried running this code):</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Sort by book title</span>
<span style="color: #000088;">$books</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">sort</span><span style="color: #009900;">&#40;</span>
    <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$book1</span><span style="color: #339933;">,</span> <span style="color: #000088;">$book2</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #990000;">strcmp</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$book1</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #339933;">,</span> <span style="color: #000088;">$book2</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Sort by publisher year, author</span>
<span style="color: #000088;">$books</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">sort</span><span style="color: #009900;">&#40;</span>
    <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$book1</span><span style="color: #339933;">,</span> <span style="color: #000088;">$book2</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$book1</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">publish_year</span> <span style="color: #339933;">==</span> <span style="color: #000088;">$book2</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">publish_year</span><span style="color: #009900;">&#41;</span>
            <span style="color: #b1b100;">return</span> <span style="color: #990000;">strcmp</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$book1</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">author</span><span style="color: #339933;">,</span> <span style="color: #000088;">$book2</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">author</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #b1b100;">return</span> <span style="color: #990000;">strcmp</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$book2</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">publish_year</span><span style="color: #339933;">,</span> <span style="color: #000088;">$book1</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">publish_year</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>It&#8217;s a little bit harder to read and maybe understand, but basically you can pass whatever comparison function you&#8217;d like. Sort function can use simple for-loop-inside-for-loop or <a href="http://uk.php.net/manual/en/function.usort.php">usort</a> and compare all elements with your function</p>
<p>Lambda functions are not replacement for __cal() and should be used cleverly, search and filtering with lambda functions is only one example of how useful they are. In short, lambda functions allows you to create small dynamic functions which can be used to expand and modify normal functions behaviour. </p>
]]></content:encoded>
			<wfw:commentRss>http://dev.juokaz.com/php/lambda-function-coming-to-php/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
