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.

Model

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 :)
  $db;

  // try to connect to the database
  try
  {
    $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();
    include('view/error.php');
    die;
  }
}

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
  try
  {
    $query = "SELECT \*
              FROM content
              ORDER BY id DESC";
    $statement = $db->prepare($query);
    $statement->execute();
    $results = $statement->fetchAll();
    $statement->closeCursor();

    // return query results
    return $results;
  }
  // catch if our query goes wrong
  catch (PDOException $e)
  {
    $errorMessage = $e->getMessage();
    include('view/error.php');
    die;
  }
}

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

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.

include('model/model.php');

// 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
else
{
  include('view/home.php');
  exit();
}

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

  // if action=blog, call runBlog
  case 'blog':
    showBlog();
    break;

  // 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
  include('view/blog.php');
}

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…

View

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:

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

// include the beginning html produced by header.php
include('inc/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"\])); ?>
      </h4>
    </div>

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

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

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

// include the closing html in the footer
include('inc/footer.php');
?>

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.