<?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/"
	>

<channel>
	<title>nemetral.net &#187; Patterns</title>
	<atom:link href="http://nemetral.net/category/patterns/feed/" rel="self" type="application/rss+xml" />
	<link>http://nemetral.net</link>
	<description>Insightful posts on design and code.</description>
	<pubDate>Mon, 18 May 2009 19:39:39 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>MVC dilemma</title>
		<link>http://nemetral.net/2008/10/15/mvc-dilemma/</link>
		<comments>http://nemetral.net/2008/10/15/mvc-dilemma/#comments</comments>
		<pubDate>Wed, 15 Oct 2008 21:18:42 +0000</pubDate>
		<dc:creator>nemetral</dc:creator>
		
		<category><![CDATA[Patterns]]></category>

		<category><![CDATA[ask]]></category>

		<guid isPermaLink="false">http://nemetral.net/?p=274</guid>
		<description><![CDATA[The most interesting questions often arise after theory has been explained, when getting hands dirty trying to write some code, organize and design a software architecture or start compiling existing snippets into a comprehensive framework. Following my posts on MVC (see and digg the "A gentle introduction to MVC" series: Part 1, Part 2 and Part 3), a reader recently asked me a couple of questions related to common MVC implementation issues.


Related posts:<ol><li><a href='http://nemetral.net/2008/08/13/a-gentle-introduction-to-mvc-part-3/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 3)'>A gentle introduction to MVC (part 3)</a> <small>In part 1, we decoupled a vanilla PHP script and...</small></li><li><a href='http://nemetral.net/2008/08/06/a-gentle-introduction-to-mvc-part-2/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 2)'>A gentle introduction to MVC (part 2)</a> <small>In part 1, we saw how to decouple a traditional...</small></li><li><a href='http://nemetral.net/2008/07/31/a-gentle-introduction-to-mvc-part-1/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 1)'>A gentle introduction to MVC (part 1)</a> <small>MVC is certainly the widest spread architectural pattern in today's...</small></li></ol>]]></description>
			<content:encoded><![CDATA[<p>The most interesting questions often arise after theory has been explained, when getting hands dirty trying to write some code, organize and design a software architecture or start compiling existing snippets into a comprehensive framework. Following my posts on MVC (see and digg the &#8220;A gentle introduction to MVC&#8221; series: <a href="http://nemetral.net/2008/07/31/a-gentle-introduction-to-mvc-part-1/">Part 1</a>, <a href="http://nemetral.net/2008/08/06/a-gentle-introduction-to-mvc-part-2/">Part 2</a> and <a href="http://nemetral.net/2008/08/13/a-gentle-introduction-to-mvc-part-3/">Part 3</a>), a reader recently asked me a couple of questions related to common MVC implementation issues.<span id="more-274"></span></p>
<blockquote><p>I had a couple of questions with respect to your articles on gentle introduction to MVC. I *really* want to understand MVC. I have little experience with web development, so the things that I develop look &#8220;okay&#8221; on the surface, but they are messy underneath. I read so much about MVC that confused the heck out of me but then I finally came across your simple intro, and I think it&#8217;s a really nice start for me. If you wrote a book about more on the concept, I&#8217;d be the first to buy it. I think that I understand the general idea, but I think I&#8217;m having a tricky time with implementation. I would *really* appreciate if you could answer a couple of questions..</p></blockquote>
<p><strong>1. Mapping between controllers and models:</strong></p>
<blockquote><p>As part of a lab booking system that I&#8217;m working on, one screen handles the showing of existing bookings, addition of new bookings, and deletion of bookings. I call it &#8220;SAD&#8221; (show, add, delete). I&#8217;m having trouble with the SAD controller and SAD model. In my test &#8220;router&#8221;, I call the SAD controller if I see (through POST) the need to show/add/delete bookings. The SAD controller instantiates the SAD model .. it&#8217;s not quite clear if there&#8217;s always a one-to-one mapping between a view, controller, and model or whether my concept of a SAD controller and SAD model right from the get-go isn&#8217;t correct?</p></blockquote>
<p>MVC is to be understood as a general guidance regarding code decoupling and organization. As such, there is no strict MVC rule requiring to map certain controllers to certain models. MVC can be implemented in various ways: the diversity of existing frameworks is certainly the best evidence of it. Back to your question: your concept of one SAD controller and one SAD model is right. I wouldn&#8217;t call it &#8220;SAD&#8221; though but rather &#8220;Bookings&#8221;, because the &#8220;SAD&#8221; operations can be executed on many different types of data (blog posts, users, images etc.): I personally always call controllers and associated models by the type of data they represent (as many other <a href="http://codeigniter.com">CodeIgniter</a> hackers do) knowing that similar operations will be executed on them all (what you call &#8220;SAD&#8221;, which is by the way usually dubbed as <a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> for Create, Read, Update and Delete). Concerning the router: I usually prefer to rely on GET variables rather than POST variables (see <a href="http://nemetral.net/2008/06/25/the-pursuit-of-apiness-part-3/">my post about REST</a>), i.e. configure the router so that it loads the controller when specific URLs are called. Both my controller and model are objects: for my controller, the object&#8217;s name would here be <strong>Bookings</strong> and each action I can undertake would be a method in my object. Here is some sample code for the object&#8217;s structure:</p>
<pre>&lt;?php

class Bookings
{

   public function add()
   {
      // code goes here
   }

   public function edit()
   {
      // code goes here
   }

   public function delete()
   {
      // code goes here
   }
}

?&gt;</pre>
<p>Each one of these methods would be bound to a specific URL:</p>
<ul>
<li>the <strong>add</strong> method would be bound to http://example.com/bookings/add</li>
<li>the <strong>edit</strong> method would be bound to http://example.com/bookings/edit</li>
<li>the <strong>delete</strong> method would be bound to http://example.com/bookings/delete</li>
</ul>
<p>The router&#8217;s job is to effectively bind the URLs to the correct controller and methods (see some code snippets in <a href="http://nemetral.net/2008/08/13/a-gentle-introduction-to-mvc-part-3/">Part 3</a> of my MVC series of post). Some methods may require a model, some other may not: this is why it is a good practice to instantiate the model from the called method of the controller. Say the <strong>add</strong> method requires the Bookings model, then I would instantiate it inside the method. Concerning the view, there will certainly not be a one-to-one mapping between the Bookings controller and the Bookings view: I need a specific view with a HTML form to <strong>add</strong> bookings, another one with another form to <strong>edit</strong> existing bookings but I don&#8217;t need a view for bookings <strong>deletion</strong>. These views can be seen as &#8220;sub views&#8221; (only the HTML forms) which can in turn be embedded into a more general view called a <strong>layout</strong>. To summarize, I would have a Bookings controller instantiated by the router, a Bookings model instantiated within the controller&#8217;s methods (if needed), a Bookings HTML layout (containing the <code>&lt;head&gt;</code> and most of the <code>&lt;body&gt;</code> tags) and several sub views inserted inside the layout depending on the controller&#8217;s method called.</p>
<p><strong>2. User authentication</strong></p>
<blockquote><p>Now, let&#8217;s say that I want to add a booking - that is, a user types a booking name onto the SAD (view) , and clicks the &#8220;NEW&#8221; button. Is it the SAD controllers job to determine whether the user has access to write the booking or not and then to pass the request on to the SAD model for the actual write? Right now, $_SESSION['access'] has that detail, and the controller checks it, but I don&#8217;t know if that&#8217;s right. When it comes to actually writing the booking &#8212; the SAD model just uses a PHP class called &#8220;booking&#8221; that abstracts the booking idea (XML files for bookings). However, do I need to have a stub function for the &#8220;write()&#8221; call from class Booking in the SAD model class so that the controller can call it without having any understanding about the details of how a booking is stored?</p></blockquote>
<p>Checking whether a user is allowed to interact with data is indeed part of the controller&#8217;s job, so what you&#8217;re doing there is perfectly in line with MVC principles. First the router maps a URL to a controller and a specific method; then the called method will find who the user is, what he can or can&#8217;t do and will therefore allow him to perform a specific action or not. If the action requires interaction with data, then the controller will delegate the task to its model (which in turn will typically be an object with methods like <code>add()</code>, <code>edit()</code>, <code>delete()</code> etc.). Either the model&#8217;s methods directly call the database and perform the action, or you can insert another layer of abstraction and further delegate the job to a specific class so that you can easily switch storage support (database, XML files etc.) later on for example. So the answer is: it mainly depends on the complexity of your project. Either you know you&#8217;ll stick to XML files and you can directly write the code in the model&#8217;s methods, or you&#8217;re not sure about it and call a third-party library to handle it.</p>
<p><strong>3. Designing methods in the controller&#8217;s object:</strong></p>
<blockquote><p>I then have another class called &#8220;BookingDatabase&#8221; which knows how to see a list of all bookings, check if one exists, etc. If I want to check if a booking exists in the SAD controller before I call the &#8220;add booking&#8221; function in the SAD model, do I need to have a stub for the &#8220;exists&#8221; function from the BookingDatabase class in the SAD model as well so that the controller can check if a booking exists before writing it?<br />
Now, let&#8217;s say I have another screen &#8212; the &#8220;EDIT&#8221; screen. I would then have an EDIT model and an EDIT controller &#8212; but this would need to write bookings as well &#8212; would the &#8220;edit&#8221; model then need to have it&#8217;s own stub of the booking classes write function?<br />
Assuming that it makes sense to have an add_booking function in the SAD model &#8212; does it make sense to have one in the controller as well? The one checks that the user has access to write the booking, that the booking doesn&#8217;t already exist, that the booking name is valid (using functions from the model) and then calls the add_booking function from the SAD model to write the booking?</p></blockquote>
<p>According to the structure I previously suggested, the <strong>edit</strong> action should be handled by the Bookings controller together with the Bookings model. So the <strong>edit</strong> feature would be implemented as a method in the Bookings controller, bound to a specific method in the Bookings model in charge of effectively editing the selecting records (through a third-party library or not). This method would call the main layout of the application but would insert a specific view in it: the edit view containing the HTML form. The other point you raise here is correct: you can check if a booking already exists in the Bookings controller by calling a specific method in the Bookings model. And the whole process you describe concerning the add_booking function is perfectly in line with MVC principles too.</p>
<p><strong>4. Enhancing the views</strong></p>
<blockquote><p>A couple of my views have a couple of small associated javascript functions. Where do they go? Do they remain in the view? I&#8217;ve stuck them in the &#8220;controllers&#8221; directory in a separate .js files, added them to the view files.</p></blockquote>
<p>Views are basically HTML files, and as such they can be enhanced with CSS and JavaScript. So these external sheets should be located in the same directory than the views. That said, this kind of organization depends on the framework you&#8217;re working with: with <a href="http://codeigniter.com">CodeIgniter</a>, views are located far away in the arborescence and it&#8217;s a pain to insert CSS and JavaScript sheets, so I usually relocate them just one folder away from the root. As they can be located anywhere, it&#8217;s better to choose a folder close to the root as it&#8217;s easier to call them from the HTML views.</p>
<p><strong>Conclusion</strong></p>
<p>Almost everything I know in computer science was learnt the hard way (trial-and-error) or by reading tutorials or forums where hackers kindly explained stuff down to implementation details. Now that I have some experience and background in the industry, I am particularly glad to share what I know with you all. Don&#8217;t hesitate to send me questions and I shall publish an answer that will surely be useful to everybody.</p>


<p>Related posts:<ol><li><a href='http://nemetral.net/2008/08/13/a-gentle-introduction-to-mvc-part-3/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 3)'>A gentle introduction to MVC (part 3)</a> <small>In part 1, we decoupled a vanilla PHP script and...</small></li><li><a href='http://nemetral.net/2008/08/06/a-gentle-introduction-to-mvc-part-2/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 2)'>A gentle introduction to MVC (part 2)</a> <small>In part 1, we saw how to decouple a traditional...</small></li><li><a href='http://nemetral.net/2008/07/31/a-gentle-introduction-to-mvc-part-1/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 1)'>A gentle introduction to MVC (part 1)</a> <small>MVC is certainly the widest spread architectural pattern in today's...</small></li></ol></p>]]></content:encoded>
			<wfw:commentRss>http://nemetral.net/2008/10/15/mvc-dilemma/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A gentle introduction to MVC (part 3)</title>
		<link>http://nemetral.net/2008/08/13/a-gentle-introduction-to-mvc-part-3/</link>
		<comments>http://nemetral.net/2008/08/13/a-gentle-introduction-to-mvc-part-3/#comments</comments>
		<pubDate>Wed, 13 Aug 2008 05:00:24 +0000</pubDate>
		<dc:creator>nemetral</dc:creator>
		
		<category><![CDATA[Patterns]]></category>

		<category><![CDATA[mvc]]></category>

		<category><![CDATA[pattern]]></category>

		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://nemetral.net/?p=55</guid>
		<description><![CDATA[In part 1, we decoupled a vanilla PHP script and separated the business logic from the presentation. In part 2, we added a third element in the mix called the model and dedicated to the data access layer. It is now time to spice up the coding by introducing the role of Object-Oriented Programming in a MVC architecture and release the very basis (for educational purpose only) of a MVC framework.


Related posts:<ol><li><a href='http://nemetral.net/2008/08/06/a-gentle-introduction-to-mvc-part-2/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 2)'>A gentle introduction to MVC (part 2)</a> <small>In part 1, we saw how to decouple a traditional...</small></li><li><a href='http://nemetral.net/2008/07/31/a-gentle-introduction-to-mvc-part-1/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 1)'>A gentle introduction to MVC (part 1)</a> <small>MVC is certainly the widest spread architectural pattern in today's...</small></li><li><a href='http://nemetral.net/2008/10/15/mvc-dilemma/' rel='bookmark' title='Permanent Link: MVC dilemma'>MVC dilemma</a> <small>The most interesting questions often arise after theory has been...</small></li></ol>]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://nemetral.net/2008/07/21/a-gentle-introduction-to-mvc-part-1">part 1</a>, we decoupled a vanilla PHP script and separated the business logic from the presentation. In <a href="http://nemetral.net/2008/07/28/a-gentle-introduction-to-mvc-part-2">part 2,</a> we added a third element in the mix called the model and dedicated to the data access layer. It is now time to spice up the coding by introducing the role of Object-Oriented Programming in a MVC architecture and release the very basis (for educational purpose only) of a MVC framework.<span id="more-55"></span></p>
<h2>Part 3: OOPs I&#8217;ve added objects</h2>
<p>As you all know, <strong>OOP</strong> is famous for wrapping functions and variables into higher-level elements called objects (if you&#8217;re not familiar with OOP, I suggest you have a look at the <a href="http://en.wikipedia.org/wiki/Object_oriented">Wikipedia page</a> and some tutorials). So here is how we could merge MVC and OOP for a greater <strong>code flexibility, reusability and maintainability</strong>:</p>
<ul>
<li>the controller is an object: in <a href="http://codeigniter.com">CodeIgniter</a> for example, the first segment of the URL is the name of the controller&#8217;s object and the second segment is the name of the controller&#8217;s method which needs to be run (for example, calling <code>http://community.com/members/show</code> would trigger the instantiation of the <code>members</code> object and the call of the <code>show</code> method)</li>
<li>the model is an object: as a representation and abstraction of the data, the model is also an object (let&#8217;s call it <code>members_model</code>) and contains functions such as <code>getAllMembers()</code> for example</li>
<li>the view can be an object too: with general functions such as <code>getTemplate()</code> which selects the corresponding template or <code>renderHTMLPage()</code> which fills the HTML page with the data and outputs the result; but the templates (and sub-templates) are plain PHP/HTML files (let&#8217;s call the layout template <code>members_view.php</code>)</li>
<li>the router is a plain vanilla PHP file which essentially checks the validity of the request and loads the correct controller</li>
</ul>
<p>Now if we translate these principles into actual PHP code, <strong>here is what a very raw MVC framework could look like</strong> (directly inspired from <a href="http://codeigniter.com">CodeIgniter</a>):<br />
Tree structure:</p>
<pre>index.php
   /controllers
      members.php
   /models
      members_model.php
   /views
      members_view.php
      /tpl
         header.php</pre>
<p>file: <code>index.php</code></p>
<pre>&lt;?php 

$request = preg_replace("|/*(.+?)/*$|", "\\1", $_SERVER['PATH_INFO']);
$uri = explode('/', $request);

include 'controllers/' . $uri[0] . '.php';
$controller = new $uri[0];
$controller-&gt;{$uri[1]}();

?&gt;</pre>
<ol>
<li><code>index.php</code> is called in the URL</li>
<li>takes the <code>PATH_INFO</code> (here: /members/show/) and cleans the starting and trailing slashes using a REGEX</li>
<li>explodes the URL into <code>$uri[0]</code> (name of the requested controller) and <code>$uri[1]</code> (name of the requested method)</li>
<li>instanciates the controller and calls the method</li>
</ol>
<p>file: <code>controllers/members.php</code></p>
<pre>&lt;?php

class members
{
  function show() {
    include 'models/members_model.php';
    $model = new members_model();
    $members = $model-&gt;getAllMembers();

    include 'views/members_view.php';
  }
}

?&gt;</pre>
<ol>
<li>to simplify, there is no constructor and the function <code>show()</code> is directly run</li>
<li>the method <code>show()</code> loads and instanciates the correct model, calls the method to get all the members and fills the <code>$members</code> variable with the data</li>
<li>then the method <code>show()</code> loads the correct view: the latter is automatically parsed (the data contained in the <code>$members</code> variable is inserted in-between HTML tags) and output</li>
</ol>
<p>file: <code>models/members_model.php</code></p>
<pre>&lt;?php

class members_model
{
   function members_model() {
     $connection = mysql_connect('host', 'user', 'password');
     mysql_select_db('database', $connection);
   }

   function getAllMembers() {
     $data = mysql_query('SELECT name FROM members');
     $members = array();
     while ($item = mysql_fetch_array($data)) {
       $members[] = $item['name'];
     }
     return $members;
   }
}</pre>
<ol>
<li>there is a constructor establishing once for all the connection to the database</li>
<li>the method <code>getAllMembers()</code> queries the database, extracts the members&#8217; names and returns them through an array</li>
</ol>
<p>file: <code>views/members_view.php</code></p>
<pre>&lt;html&gt;
  &lt;?php include 'views/tpl/header.php'; ?&gt;
  &lt;h1&gt;Members of community.com:&lt;/h1&gt;
  &lt;ul&gt;
  &lt;?php for ($i = 0; $i &lt; count($members); $i++) : ?&gt;
    &lt;li&gt;Member #&lt;?php echo $i + 1; ?&gt;: &lt;?php echo $members[$i]; ?&gt;&lt;/li&gt;
  &lt;?php endfor; ?&gt;
  &lt;/ul&gt;
&lt;/html&gt;</pre>
<p>file: <code>views/tpl/header.php</code></p>
<pre>&lt;head&gt;
  &lt;title&gt;Community.com rocks!&lt;/title&gt;
&lt;/head&gt;</pre>
<ol>
<li>the main layout <code>members_view.php</code> is included by the controller and therefore automatically parsed</li>
<li>the layout includes a reusable template for the header</li>
</ol>
<p><em>Note: this code is for educational purpose only. </em></p>
<p>As you can see, building a <strong>OO MVC architecture</strong> is not that difficult. Please bear in mind that the code above is a basic way of achieving a MVC architecture and a lot of things could be improved:</p>
<ul>
<li>first thing to do is to dramatically enhance the router file: there is no checking on whether the requested controller exists or not, and is accessible or not (<strong>this is a huge security hole</strong>)</li>
<li>instead of getting connected to the database in the model&#8217;s constructor, why not creating a <strong>model superclass</strong> managing the database connection and make each model an extension of this superclass? This way we could use several models from our controller without worrying about being already connected to the database or not</li>
<li>in the same way, why not creating a <strong>controller superclass</strong> with common features and make each controller an extension of this superclass?</li>
</ul>
<p>Now <a href="http://codeigniter.com">CodeIgniter</a> has all that.. and much more. It is secure, lightweight and brillantly coded. If you want to start coding MVC, <a href="http://codeigniter.com">CodeIgniter is a must have</a>!</p>


<p>Related posts:<ol><li><a href='http://nemetral.net/2008/08/06/a-gentle-introduction-to-mvc-part-2/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 2)'>A gentle introduction to MVC (part 2)</a> <small>In part 1, we saw how to decouple a traditional...</small></li><li><a href='http://nemetral.net/2008/07/31/a-gentle-introduction-to-mvc-part-1/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 1)'>A gentle introduction to MVC (part 1)</a> <small>MVC is certainly the widest spread architectural pattern in today's...</small></li><li><a href='http://nemetral.net/2008/10/15/mvc-dilemma/' rel='bookmark' title='Permanent Link: MVC dilemma'>MVC dilemma</a> <small>The most interesting questions often arise after theory has been...</small></li></ol></p>]]></content:encoded>
			<wfw:commentRss>http://nemetral.net/2008/08/13/a-gentle-introduction-to-mvc-part-3/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A gentle introduction to MVC (part 2)</title>
		<link>http://nemetral.net/2008/08/06/a-gentle-introduction-to-mvc-part-2/</link>
		<comments>http://nemetral.net/2008/08/06/a-gentle-introduction-to-mvc-part-2/#comments</comments>
		<pubDate>Wed, 06 Aug 2008 05:00:44 +0000</pubDate>
		<dc:creator>nemetral</dc:creator>
		
		<category><![CDATA[Patterns]]></category>

		<category><![CDATA[mvc]]></category>

		<category><![CDATA[pattern]]></category>

		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://nemetral.net/?p=49</guid>
		<description><![CDATA[In part 1, we saw how to decouple a traditional vanilla PHP script so as to separate business logic from presentation. This was the biggest step to make: from now on, we are just going to finetune this separation by adding a 3rd guy in the equation: the model. Ladies and gentlemen, this is part 2 of A gentle introduction to MVC.


Related posts:<ol><li><a href='http://nemetral.net/2008/08/13/a-gentle-introduction-to-mvc-part-3/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 3)'>A gentle introduction to MVC (part 3)</a> <small>In part 1, we decoupled a vanilla PHP script and...</small></li><li><a href='http://nemetral.net/2008/07/31/a-gentle-introduction-to-mvc-part-1/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 1)'>A gentle introduction to MVC (part 1)</a> <small>MVC is certainly the widest spread architectural pattern in today's...</small></li><li><a href='http://nemetral.net/2008/10/15/mvc-dilemma/' rel='bookmark' title='Permanent Link: MVC dilemma'>MVC dilemma</a> <small>The most interesting questions often arise after theory has been...</small></li></ol>]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://nemetral.net/2008/07/21/a-gentle-introduction-to-mvc-part-1">part 1</a>, we saw how to decouple a traditional vanilla PHP script so as to separate business logic from presentation. This was the biggest step to make: from now on, we are just going to finetune this separation by adding a 3rd guy in the equation: <strong>the model</strong>. Ladies and gentlemen, this is part 2 of <em>A gentle introduction to MVC</em>.<span id="more-49"></span></p>
<h2>Part 2: fully MVC-powered goodness</h2>
<p>MVC stands for <strong>Model/View/Controller</strong>. It&#8217;s a software design pattern advocating the use of three layers:</p>
<ul>
<li>the <strong>model</strong>: the model is the data access layer, the one responsible for gathering the data asked by the request (i.e. functions like <code>getAllMembers()</code> returning a PHP array with all the members in it, or  <code>addMember($name, $age, $city)</code> to add a new member to the database)</li>
<li>the <strong>view</strong>: the view is the presentation layer in charge of generating the output (i.e. the final HTML webpage featuring the names of the members with PHP used as a template language as in <code>&lt;li&gt;&lt;?php echo $member['name']; ?&gt;&lt;/li&gt;</code>)</li>
<li>the <strong>controller</strong>: the controller is aimed at coordinating the whole process by analysing the request, running the corresponding model to get the data (i.e. calling <code>getAllMembers()</code> and put the return array in the PHP variable <code>$members</code>), call the corresponding view (i.e. <code>include 'tpl/template.php'</code>) and fill it with the data (i.e. <code>$members</code>), and then send the final output back</li>
</ul>
<p>Here is a simple graph to better understand the MVC design pattern:</p>
<p><img class="alignnone size-full wp-image-50" title="200807-model-view-controller-mvc" src="http://nemetral.net/wp-content/uploads/200807-model-view-controller-mvc.png" alt="" width="500" height="350" /></p>
<p>This new architecture gives more <strong>flexibility</strong> when building the application:</p>
<ul>
<li>the data access layer is outsourced to the <strong>model</strong> so that we can work with an <strong>abstraction of data</strong>: the actual storage of data may be a database, XML files or a hash table, we will still access the list of members through the function <code>getAllMembers()</code></li>
<li>the presentation layer is outsourced to the <strong>view</strong>: if we want the output to be a RSS feed instead of a HTML page, we just have to change the view <strong>without interfering</strong> with the logic or the data access</li>
</ul>
<p>As you can see, MVC is extremely powerful because it makes it possible to split down the script in <strong>naturally independant</strong> parts, which in turn makes the old <strong>reusability</strong> dream come true: for example, if we want to output both a HTML page and a RSS feed featuring all the members of community.com, we can reuse the same model and simply create two different templates (say <code>'tpl/template.php'</code> and <code>'tpl/rss.php'</code>).</p>
<p>Now let&#8217;s turn to a substantial implementation of the MVC design pattern. Calling directly the controller through <code>http://community.com/members.php</code> can be enhanced through a little bit more of decoupling: instead of calling directly the script, we will call a <strong>single-entry point</strong> called the <strong>router</strong> specifying that we want to display the members&#8217; page, and this router will analyze the request, understand that we want to display the members&#8217; page and run the <code>members.php</code> controller. In <a href="http://codeigniter.com">CodeIgniter</a> for example, the single-entry point is called <code>index.php</code> and if we want to call the members controller, we have to type the following url: <code>http://community.com/index.php/members</code>.  We could also imagine a less-sexy <code>http://community.com/index.php?controller=members</code> or, on the contrary, get rid of the router through some URL rewriting and just having to call an elegant <code>http://community.com/members</code>.</p>
<p><img class="alignnone size-full wp-image-54" title="200807-model-view-controller-mvc-implementation" src="http://nemetral.net/wp-content/uploads/200807-model-view-controller-mvc-implementation.png" alt="" width="500" height="430" /></p>
<p>Here is what we have added or clarified in this example of <strong>MVC implementation</strong>:</p>
<ul>
<li>the router is now the single entry-point of the application which analyzes each request and loads the corresponding controller</li>
<li>the model interfaces with a database (once again, it could be a set of XML files or any other way of storing data, we would just have to rewrite the model without worrying about the final output providing that we deliver the expected data)</li>
<li>the view now becomes a main layout which in turn can include reusable sub-templates (this is directly inspired from Ruby on Rails and has been reproduced in many web frameworks)</li>
</ul>
<p><em>(Go to <a href="http://nemetral.net/2008/08/13/a-gentle-introduction-to-mvc-part-3/">part 3</a>)</em></p>


<p>Related posts:<ol><li><a href='http://nemetral.net/2008/08/13/a-gentle-introduction-to-mvc-part-3/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 3)'>A gentle introduction to MVC (part 3)</a> <small>In part 1, we decoupled a vanilla PHP script and...</small></li><li><a href='http://nemetral.net/2008/07/31/a-gentle-introduction-to-mvc-part-1/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 1)'>A gentle introduction to MVC (part 1)</a> <small>MVC is certainly the widest spread architectural pattern in today's...</small></li><li><a href='http://nemetral.net/2008/10/15/mvc-dilemma/' rel='bookmark' title='Permanent Link: MVC dilemma'>MVC dilemma</a> <small>The most interesting questions often arise after theory has been...</small></li></ol></p>]]></content:encoded>
			<wfw:commentRss>http://nemetral.net/2008/08/06/a-gentle-introduction-to-mvc-part-2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A gentle introduction to MVC (part 1)</title>
		<link>http://nemetral.net/2008/07/31/a-gentle-introduction-to-mvc-part-1/</link>
		<comments>http://nemetral.net/2008/07/31/a-gentle-introduction-to-mvc-part-1/#comments</comments>
		<pubDate>Thu, 31 Jul 2008 05:00:21 +0000</pubDate>
		<dc:creator>nemetral</dc:creator>
		
		<category><![CDATA[Patterns]]></category>

		<category><![CDATA[mvc]]></category>

		<category><![CDATA[pattern]]></category>

		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://nemetral.net/?p=33</guid>
		<description><![CDATA[MVC is certainly the widest spread architectural pattern in today's webdevelopment landscape. Brought back to fashion by Ruby on Rails from 2004 on, it has been translated and implemented into many languages and more than 100 web frameworks. This illustrated three-part is aimed at helping you cross the gap between a traditionnal vanilla PHP script and a full MVC implementation.


Related posts:<ol><li><a href='http://nemetral.net/2008/08/13/a-gentle-introduction-to-mvc-part-3/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 3)'>A gentle introduction to MVC (part 3)</a> <small>In part 1, we decoupled a vanilla PHP script and...</small></li><li><a href='http://nemetral.net/2008/08/06/a-gentle-introduction-to-mvc-part-2/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 2)'>A gentle introduction to MVC (part 2)</a> <small>In part 1, we saw how to decouple a traditional...</small></li><li><a href='http://nemetral.net/2008/07/11/the-pursuit-of-apiness-part-5/' rel='bookmark' title='Permanent Link: The pursuit of APIness (part 5)'>The pursuit of APIness (part 5)</a> <small>XML-RPC is damn easy to use and many projects still...</small></li></ol>]]></description>
			<content:encoded><![CDATA[<p>MVC is certainly the <strong>widest spread architectural pattern</strong> in today&#8217;s webdevelopment landscape. Brought back to fashion by Ruby on Rails from 2004 on, it has been translated and implemented into many languages and <a href="http://en.wikipedia.org/wiki/Model-view-controller#Implementations_of_MVC_as_web-based_frameworks">more than 100 web frameworks</a>. This illustrated three-part is aimed at helping you cross the gap between a traditionnal vanilla PHP script and a full MVC implementation.<span id="more-33"></span></p>
<h2>Part 1: decoupling a traditional webpage</h2>
<p>Remember <a href="http://nemetral.net/2008/06/10/the-pursuit-of-apiness-part-1/">community.com</a>? Here is what could be the server-side script used to generate a page featuring all the website&#8217;s members (assuming an average use &amp; level of vanilla PHP):</p>
<pre>&lt;html&gt;

  &lt;?php include 'inc/header.php'; ?&gt;

  &lt;h1&gt;Members of community.com:&lt;/h1&gt;
  &lt;?php
    // INITIALIZING THE DATABASE
    $connection = mysql_connect('host', 'user', 'password');
    mysql_select_db('database', $connection);
    // PULLING OUT THE DATA
    $data = mysql_query('SELECT name FROM members');
    // DISPLAYING THE DATA
    echo '&lt;ul&gt;';
    $i = 1;
    while ($member = mysql_fetch_array($data)) {
       echo '&lt;li&gt;Member #' . $i . ': '. $member['name'] . '&lt;/li&gt;';
       $i++;
    }
    echo '&lt;/ul&gt;';
  ?&gt;

&lt;/html&gt;</pre>
<p>with <code>inc/header.php</code> being like:</p>
<pre> &lt;head&gt;
    &lt;title&gt;Community.com rocks!&lt;/title&gt;
 &lt;/head&gt;</pre>
<p><em>Note: this is still very basic HTML without DOCTYPE </em></p>
<p>Since data is pulled out from the database in the middle of HTML tags, each time you need to display the members&#8217; names, you need to rewrite the PHP/SQL snippet, which makes it more difficult for your code to be <strong>maintainted</strong>. Still, although not being a flawless, this is not dumb writing neither: we can see <strong>the ghost of a decoupling</strong> through the use of <code>include</code>, which makes it possible to start splitting the code into reusable parts (e.g. the header).</p>
<p>Here are a few things we could do to enhance the organization of this script:</p>
<ul>
<li>remove all the PHP logic (e.g. querying the database, formatting data etc.) from in-between HTML tags and paste it all above the first <code>&lt;html&gt;</code> tag</li>
<li>use PHP variables (filled with the data pulled out from the database) to carry data in-between the HTML tags</li>
<li>step further in decoupling and split the script into two files: one for the logic and the other for the presentation (based on the PHP variables)</li>
</ul>
<p>Here is a simple graph to better understand the process:</p>
<p><img class="alignnone size-full wp-image-46" title="200807-decoupling" src="http://nemetral.net/wp-content/uploads/200807-decoupling.png" alt="" width="500" height="264" /></p>
<p><strong>Step 1</strong> is the original PHP script where business logic (which query to execute, pulling out data from the database etc.) is mixed with HTML tags. In <strong>Step 2</strong>, we isolate the logic at the beginning of the script, keep the HTML tags at the bottom of the script and link the two using PHP variables. <strong>Step 3</strong> is the final step: we simply split the script in two files (one for the logic and the other for the HTML presentation). Applied to our code, here would be the result at <strong>step 3</strong>:</p>
<pre>&lt;?php
  $connection = mysql_connect('host', 'user', 'password');
  mysql_select_db('database', $connection);

  $data = mysql_query('SELECT name FROM members');
  $members = array();
  while ($item = mysql_fetch_array($data)) {
    $members[] = $item['name'];
  }

  include 'tpl/template.php';
?&gt;</pre>
<p>with <code>tpl/template.php</code> being like:</p>
<pre>&lt;html&gt;
  &lt;?php include 'tpl/header.php'; ?&gt;
  &lt;h1&gt;Members of community.com:&lt;/h1&gt;
  &lt;ul&gt;
  &lt;?php foreach ($members as $i =&gt; $member) : ?&gt;
    &lt;li&gt;Member #&lt;?php echo $i + 1; ?&gt;: &lt;?php echo $member; ?&gt;&lt;/li&gt;
  &lt;?php endforeach; ?&gt;
  &lt;/ul&gt;
&lt;/html&gt;</pre>
<p><em> </em></p>
<p><em>Note: when using PHP as a template engine (this is what we are doing in the second file), it is quite common to use <a href="http://php.net/control-structures.alternative-syntax">alternative structures</a>. Also note that I changed the &#8216;inc&#8217; directory for a &#8216;tpl&#8217; directory, the latter being in charge of gathering all template files (so <code>tpl/header.php</code> in <strong>step 3</strong> is the same file than <code>inc/header.php</code> in <strong>step 1</strong>).</em></p>
<p>Once parsed, you will get the following HTML output (supposing there are only two members Anna and Lisa):</p>
<pre>&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Community.com rocks!&lt;/title&gt;
  &lt;/head&gt;
  &lt;h1&gt;Members of community.com:&lt;/h1&gt;
  &lt;ul&gt;
    &lt;li&gt;Member #1: Anna&lt;/li&gt;
    &lt;li&gt;Member #2: Lisa&lt;/li&gt;
  &lt;/ul&gt;
&lt;/html&gt;</pre>
<p>Let&#8217;s now zoom out from the script and have a look at the whole request/response structure. When calling <code>http://community.com/members.php</code>, here it what happens:</p>
<ol>
<li>members.php gets connected to the database, pulls out the members&#8217; names and fills an array with them (called <code>$members</code>)</li>
<li>members.php includes the template file in which <code>$members</code> is looped through so as to produce the final HTML</li>
</ol>
<p>This could be called a View/Controller architecture, where <code>members.php</code> is the controller and <code>tpl/template.php</code> the view:</p>
<p><img class="alignnone size-full wp-image-47" title="200807-decoupling-vc" src="http://nemetral.net/wp-content/uploads/200807-decoupling-vc.png" alt="" width="500" height="264" /></p>
<p>Proceeding like this makes it possible to <strong>separate logic from presentation</strong>: first we run all the queries and then we generate the HTML page using PHP variables.</p>
<p><em>(Go to <a href="http://nemetral.net/2008/08/06/a-gentle-introduction-to-mvc-part-2/">part 2</a>)<br />
</em></p>
<p><a href="http://codeigniter.com/forums/viewthread/86844/#438082">A comments thread is available on CodeIgniter Forums</a></p>


<p>Related posts:<ol><li><a href='http://nemetral.net/2008/08/13/a-gentle-introduction-to-mvc-part-3/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 3)'>A gentle introduction to MVC (part 3)</a> <small>In part 1, we decoupled a vanilla PHP script and...</small></li><li><a href='http://nemetral.net/2008/08/06/a-gentle-introduction-to-mvc-part-2/' rel='bookmark' title='Permanent Link: A gentle introduction to MVC (part 2)'>A gentle introduction to MVC (part 2)</a> <small>In part 1, we saw how to decouple a traditional...</small></li><li><a href='http://nemetral.net/2008/07/11/the-pursuit-of-apiness-part-5/' rel='bookmark' title='Permanent Link: The pursuit of APIness (part 5)'>The pursuit of APIness (part 5)</a> <small>XML-RPC is damn easy to use and many projects still...</small></li></ol></p>]]></content:encoded>
			<wfw:commentRss>http://nemetral.net/2008/07/31/a-gentle-introduction-to-mvc-part-1/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
