Moving to MVC

Now that I had a working blog page that worked, I needed to to set up my site to be a lot more friendly to generating and displaying various posts. The best way to handle this was to use the model-view-controller architecture.


What’s the model?
Simply put, the model is a representation of the data used in an application (in this case, the database). Here’s where everything data-related is stored

I extracted out several functions from my original code. The first function, getDBConnection, attempts to create a connection to the database, and if successful, returns a PDO $db. If the attempt fails, it gets the PDO exception message and includes the error.php file which contains the error page.

// get a connection to the database
function getDBConnection()
  // variables for SQL connection
  $host = 'localhost';
  $dbname = 'blog\_db';
  $user = 'blog\_view';
  $pass = 'P@ssw0rd!';  // not the real password :)

  // try to connect to the database
    $db = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $pass);
    // return the database object
    return $db;
  // catch if we can't connect
  catch (PDOException $e)
    $errorMessage = $e->getMessage();

I also extracted out and created getAllPosts, for querying and returning the posts within my blog database. This function calls getDBConnection, then queries the database for all entries in it. Similar to getDBConnection, if the query is successful, it returns the results as $results, or the exception is returned and the error.php file is included.

// get all posts in the database
function getAllPosts()
  $db = getDBConnection();

  // try to query the database and get results
    $query = "SELECT \*
              FROM content
              ORDER BY id DESC";
    $statement = $db->prepare($query);
    $results = $statement->fetchAll();

    // return query results
    return $results;
  // catch if our query goes wrong
  catch (PDOException $e)
    $errorMessage = $e->getMessage();

That’s it for now in regards to the model, I moved on to the controller…


What’s the controller?
Simply put, the controller is a controls what data from model is sent to the view (which we’ll see further on). It also interprets every click made on the site.

The controller was the portion of the MVC architecture that wasn’t already a part of my previously made simple blog. For the sake of brevity, I’ve only included the portions that are used in diplaying the blog. For my site, the controller is used along with a URL parameter and value. In this case, I’m using the parameter action and looking for it’s value to determine what action a user wants to take.

That being said, my controller looks to see if the parameter action has been set, and if so, assigns it to the php variable $action. It then uses a switch to determine if the value of the action parameter matches up with my pre-defined actions and runs the appropriate function that interacts with the model and controller.


// if an action is set (i.e. /controller.php?action=blog)
if (isset($\_GET\['action'\]))
  // set $action as the action requested
  $action = $\_GET\['action'\];
// else, the default page is used

// switch for determining what actions to take
switch ($action)
  // other actions are here..

  // if action=blog, call runBlog
  case 'blog':

  // more actions are here...

// connects to database and gets blog posts
function showBlog()
  // get blog posts and store in $results for the view
  $results = getAllPosts();
  // include the view php/html

You can see that the last line of the showBlog function includes the blog php file, which is the last key to setting up my site to use MVC…


What’s the view?
Simply put, the view is a controls what data from model is sent to the view (which we’ll see further on). It also interprets every click made on the site.

The good new about moving to MVC is that very little has to be done in regards to the view file for the blog. Basically, we’re left with what was orginally finished last time with our connection and querying code stripped out:

// variables for header.php
$html\_title = 'Jim McKenna: Blog';
$menu\_selected = 'blog';
$title = 'Blog';

// include the beginning html produced by header.php

// print the posts to the page

// for each row returned
foreach ($results as $row)
  <!-- output the divs for the blog content -->
  <div class="blog-post">
    <div class="blog-date-col">

      <!-- echo out the date field for the row -->
      <h4 class="blog-date">
        <?php echo date("d M Y", strtotime($row\["date"\])); ?>

    <div class="blog-content-col">

      <!-- echo out the title field of the row -->
      <h2 class="blog-title">
        <?php echo $row\["title"\]; ?>

      <!-- echo out the content field of the row -->
        <?php echo $row\["content"\]; ?>

// include the closing html in the footer

More Work to Go

With this move to using MVC, I’ve opened myself up to quite a number of possibilities and room for expansion. If I want to make more pages, I can simply slip in an addional view file and case/function combination in my controller. If I want to order my posts, or add differnt display options, I can add another function in my model.