<?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; models</title>
	<atom:link href="http://dev.juokaz.com/tag/models/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>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>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 directory structure</title>
		<link>http://dev.juokaz.com/php/zend-framework-directory-structure</link>
		<comments>http://dev.juokaz.com/php/zend-framework-directory-structure#comments</comments>
		<pubDate>Sun, 22 Feb 2009 22:45:39 +0000</pubDate>
		<dc:creator>Juozas</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[admin]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[cms]]></category>
		<category><![CDATA[controllers]]></category>
		<category><![CDATA[frontend]]></category>
		<category><![CDATA[help]]></category>
		<category><![CDATA[models]]></category>
		<category><![CDATA[public]]></category>
		<category><![CDATA[structure]]></category>
		<category><![CDATA[views]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://dev.juokaz.com/?p=238</guid>
		<description><![CDATA[Currently I&#8217;m working on a new project which works on Zend Framework. I really like this framework and it has been my favourite for quite a long time &#8211; I especially like it&#8217;s standalone components and huge space for your personal programming style. But&#8230; I don&#8217;t know how to correctly implement modularity in Zend Framework.
I [...]]]></description>
			<content:encoded><![CDATA[<p>Currently I&#8217;m working on a new project which works on <a href="http://framework.zend.com/">Zend Framework</a>. I really like this framework and it has been my favourite for quite a long time &#8211; I especially like it&#8217;s standalone components and huge space for your personal programming style. But&#8230; I don&#8217;t know how to correctly implement modularity in Zend Framework.</p>
<p>I need to have modular systems, which would allow downloading module as an archive and installing it would be as hard as unpacking it. Modules should work in their own folders and don&#8217;t require any system modifications. Also, modules needs to have different controllers and views for different website parts: backend and frontend.</p>
<p>Zend Framework <a href="http://framework.zend.com/manual/en/zend.controller.modular.html">manual</a> has examples for directory structures and suggests this modular structure:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">application<span style="color: #339933;">/</span>
    <span style="color: #339933;">*</span>module_name<span style="color: #339933;">*/</span>
        controllers<span style="color: #339933;">/</span>
            IndexController<span style="color: #339933;">.</span>php
            FooController<span style="color: #339933;">.</span>php
        models<span style="color: #339933;">/</span>
        views<span style="color: #339933;">/</span>
            scripts<span style="color: #339933;">/</span>
                index<span style="color: #339933;">/</span>
                foo<span style="color: #339933;">/</span>
            helpers<span style="color: #339933;">/</span>
            filters<span style="color: #339933;">/</span></pre></div></div>

<p>But how to distinguish between frontend and backend parts? Some solutions suggests having backend as <em>admin</em> module, but modular structure would be lost &#8211; adding new modules would require modifying <em>admin</em> module. So I decided to invent my own directories tree and came up with:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">application<span style="color: #339933;">/</span>
    <span style="color: #339933;">*</span>module_name<span style="color: #339933;">*/</span>
        controllers<span style="color: #339933;">/</span>
	    admin<span style="color: #339933;">/</span>
                 IndexController<span style="color: #339933;">.</span>php
                 FooController<span style="color: #339933;">.</span>php
	    <span style="color: #000000; font-weight: bold;">public</span><span style="color: #339933;">/</span>
                 IndexController<span style="color: #339933;">.</span>php
                 FooController<span style="color: #339933;">.</span>php
        models<span style="color: #339933;">/</span>
        views<span style="color: #339933;">/</span>
            scripts<span style="color: #339933;">/</span>
                admin<span style="color: #339933;">/</span>
		     index<span style="color: #339933;">/</span>
		     foo<span style="color: #339933;">/</span>
                <span style="color: #000000; font-weight: bold;">public</span><span style="color: #339933;">/</span>
		     index<span style="color: #339933;">/</span>
		     foo<span style="color: #339933;">/</span>
            helpers<span style="color: #339933;">/</span>
            filters<span style="color: #339933;">/</span></pre></div></div>

<p>It works perfectly (requires small bootstrap modifications), but I do not like it. What I don&#8217;t like is high depth of folders &#8211; working with files browser is really painful. Also, multiple folders share same <em>admin</em> and<em> public</em> folders, but it&#8217;s not really right &#8211; <em>admin</em> and <em>public</em> are parts of website and they should have different controllers, not controllers have different parts. So I reversed whole tree:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">application<span style="color: #339933;">/</span>
    <span style="color: #339933;">*</span>module_name<span style="color: #339933;">*/</span>
        admin<span style="color: #339933;">/</span>
            controllers<span style="color: #339933;">/</span>
                 IndexController<span style="color: #339933;">.</span>php
                 FooController<span style="color: #339933;">.</span>php
            scripts<span style="color: #339933;">/</span>
                 index<span style="color: #339933;">/</span>
		 foo<span style="color: #339933;">/</span>
        <span style="color: #000000; font-weight: bold;">public</span><span style="color: #339933;">/</span>
            controllers<span style="color: #339933;">/</span>
                 IndexController<span style="color: #339933;">.</span>php
                 FooController<span style="color: #339933;">.</span>php
            scripts<span style="color: #339933;">/</span>
                 index<span style="color: #339933;">/</span>
		 foo<span style="color: #339933;">/</span>
        models<span style="color: #339933;">/</span>
        views<span style="color: #339933;">/</span>
            helpers<span style="color: #339933;">/</span>
            filters<span style="color: #339933;">/</span></pre></div></div>

<p>I haven&#8217;t tried implementing it, but it works in theory. Having <em>admin</em> and <em>public</em> as root folders also creates possibility to add, for example, part dependant forms more easily.  However, I still don&#8217;t know which structure to choose &#8211; they all have different pros and cons, though last one seems to be most &#8220;natural&#8221;.</p>
<p>Which structure you use?</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.juokaz.com/php/zend-framework-directory-structure/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>
