Simple Blog – Example 4: MVC

Simple Blog is a multi-part series. Check out The Index

In example 1, we started out by writing some PHP scripts that executed pretty much top to bottom. In example 2, we re-factored our code and markup into reusable function and templates to minimize repetition in the development process. In example 3, we identified a couple candidate objects which we rolled into classes to enhance code maintainability. Throughout this process, we’ve extracted our data logic from our base pages, however, application logic and presentation layer are still mixed.

In this example, we’ll decouple application logic and presentation logic by moving all of our presentation logic into new files we’ll call views. Once we’ve performed this decoupling, our code will be nicely separated into three distinct types: models, views, and controllers.

Models

Our model is just the Post class we created in Example 3. I’ve renamed the file to ‘post.model.php’ and moved it into a directory called models, but other than these two administrative changes, the Post class is unchanged.

Views

Simple Blog has three views: List View, Read View, and Upsert View. The List View displays a list of posts. The Read View displays a single post. The Upsert View displays an HTML form for either creating a new post or editing an existing post. So, let’s take a look at our three views. Note, there is zero new code here, the only thing we’re changing is how the code is organized.

List View

<?php require_once(VIEW_PATH.'header.inc.php'); ?>

	<?php foreach($posts as $post): ?>

		<h4>
			<a href="read.php?id=<?php 
				echo $post->id;?>"><?php 
				echo $post->title;?>
			</a>
		</h4>

		<p>
			<?php echo $post->content;?>
			<?php echo $post->created;?>
		</p>

	<?php endforeach; ?>

<?php require_once(VIEW_PATH.'footer.inc.php'); ?>

Continue reading