Really Simple Model/View Seperation With PHP

 

I think I speak for a number of developers when I say that I strive to have my code readable and easy to maintain. This is way easier said than done as many of you know. The most familiar way of doing this is using the Model View Controller (MVC) concept.

While I see the point in the above, I do sometimes struggle with its practicality. For example, do I really need to use CakePHP, Symfony, CodeIgniter for a simple PHP based site? I agree that frameworks can be handy for larger sites, but the majority of my sites are on the smaller side.

This is the reason that I will teach you a simple way to separate your models/views with very little OO logic, and not using a framework.

Folder Structure

Start by creating a folder structure using the following:

MySQL Database Class (db.class.php)

<?php

// best practice is naming the class the same as the first part of the filename
class DB {
	var $db; // property of our class that will store our DB connection

        /*
            This function loads as soon as the class is instantiated.  Eg. $db = new DB();
            PHP5 uses __construct and PHP4 uses a function the same name as the class.  Eg. function DB()
        */
	function __construct()
	{
               // change the following credentials to match your server
		$this->db = mysqli_connect('localhost','username','password','database') or die('Unable to connect to the MySQL server.');
	}
}

NOTE: Make sure you have created a database on your MySQL server and have changed it in the above class.

Create the Products Table

Now run the following SQL query on your database using any method you wish (phpMyAdmin, SSH, etc…)

CREATE TABLE IF NOT EXISTS `products` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `description` text NOT NULL,
  PRIMARY KEY (`product_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

This creates the following fields: product_id (PRIMARY KEY), title, description, image

Insert Product Data

Do the same with the following:

INSERT INTO `trailers_products` (`product_id`, `title`, `description`) VALUES
(1, 'Hosting', 'Hosting Description'),
(2, 'Web Design', 'Web Design Description'),
(3, 'Programming', 'Programming Description'),
(4, 'SEO', 'SEO Description'),
(5, 'iPhone Development', 'iPhone Development Description');

This has inserted a couple sample products so we can see our result later on.

Product Class (products.class.php)

<?php

// include our dababase class we just created
include 'db.class.php';

/*
	NOTE: This class will extend the class we created previously

	This means that our $db variable will be accessible for our queries ($this->db)
*/
class Products extends DB {

	/*
		Simple function that will get all our products from the db and return an array of objects
	*/
	function getProducts()
	{
		$query = "SELECT product_id, title, description
				  FROM products
				  ORDER BY title";
		$result = mysqli_query($this->db, $query);

		$data = array();
		while( $row = mysqli_fetch_object($result) )
		{
			array_push($data, $row);
		}
		return $data;
	}
}

Pulling It All Together (index.php)

<?php
	// include our products class
	include_once 'classes/products.class.php';

    // instantiate our class
	$ProdModel = new Products();

    // call our user defined function which returns an array of products
    $products = $ProdModel->getProducts();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Brenelz Web Solutions - Products</title>
</head>

<body>

<h1>Products</h1>

<?php foreach( $products as $p ) :  ?>
    <h2><?php echo $p->title?></h2>
    <p><?php echo $p->description?></p>
    <hr />
<?php endforeach; ?>

</body>
</html>

Now open up index.php in your browser and see all the products that have been entered into the database!

Thoughts?

Related posts:

  1. Project Management: Simple TO-DO List
  2. How-To MySQL Table Joins


Written by brenelz

Hello everyone, I'm Brenley Dueck or better known as Brenelz. I currently run my own business called Brenelz Web Solutions which focuses primary on winnipeg website design. The web technologies I most specialize in are CSS, jQuery, AJAX, PHP, and the MySQL database. Please make sure to follow me on twitter.

 

12 Responses to “Really Simple Model/View Seperation With PHP”

  1. Chris Roane Says:

    March 10th, 2010 at 4:31 pm

    I like your simple approach. I do not agree with not using a framework type of system. Even in your simple example, you basically are creating a very basic framework, and you would have problems if they wanted to extend features on the site or have multiple pages.

    Frameworks allow the ability to quickly deploy small and medium sized websites.

  2. brenelz Says:

    March 10th, 2010 at 4:45 pm

    What frameworks do you suggest that aren’t hugely bloated like CakePHP, and Symfony. I can see using CodeIgniter possibly…

  3. Timothy McClanahan Says:

    March 10th, 2010 at 7:19 pm

    clearsilver is a pretty interesting system you might want to check out. (clearsilver.net)

  4. OIS Says:

    March 11th, 2010 at 4:36 am

    Each object will have its own connection to the database?

  5. Dimitar Velkov Says:

    March 11th, 2010 at 6:50 am

    This is similar to the Page Controller Pattern

  6. Sid Says:

    March 11th, 2010 at 7:08 am

    Use Codeigniter – once you get the hang of it (which doesn’t take long), it’s really easy to work with. You only load the classes you need, so it’s really light.

  7. thinsoldier Says:

    March 17th, 2010 at 10:13 am

    Yes this is a page “controller”.

    All that’s really shown here is a Model.

    No front-controller. No controller for each major section of the site.

    Personally, I can live without the models. The controller aspect is my favourite.

    If a single “page” has a ton of features like say:
    list all products, product search form, view product details etc…
    accessed like site.com/products.php?cmd=list or cmd=search or cmd=view&id=37
    then in the old days I’d have a ton of:
    [? if($cmd===’list’){ …code… }
    elseif($cmd===’view’){…code…}
    elseif{…etc..} … etc…

    Controllers (& a template for each controller action) are sooo much better than doing all those IFs and (to me) more important than models.

  8. thinsoldier Says:

    March 17th, 2010 at 10:15 am

    OIS: I _think_ once a connection has been made, all other attempts to connect will re-use the existing connection.

  9. Evan Byrne Says:

    March 17th, 2010 at 2:15 pm

    @brenelz, if you are looking for a feature rich PHP framework that isn’t huge, you should check out Dingo. It’s an open source framework I’ve been working on for the past couple years: http://www.dingoframework.com

  10. brenelz Says:

    March 17th, 2010 at 2:28 pm

    looks pretty cool. Very similar to CodeIgniter in syntax… I guess just more of a lightweight version?

  11. OIS Says:

    March 23rd, 2010 at 10:18 am

    thinsoldier: you _belive_. Unlike religions you can here confirm your belief is unfounded.

  12. Andrew C Says:

    March 29th, 2011 at 11:08 pm

    1. Use PDO
    2. IMO, .class.php is a silly convention, especially since the containing folder is called classes.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 
connect with me!