ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

Building a simple MVC system with PHP5

(Page 5 out of 5)

The View

Just like the Model, there are several different ways of doing the View part of our MVC system. We could use the Router to automatically load another file called something like 'view_{name}.php', but to keep this tutorial simple, we'll create a custom Template class, which can be used to show templates.

First, create a new file called 'template.php' in the 'classes' directory, and put the following code in it:

Class Template {
        private $registry;
private $vars = array();

        function __construct($registry) {
                $this->registry = $registry;
        }

}

?>

As you can see, we've now got the basic structure of our Template class. The next step is to add the following code to our index.php file, before the Router statements:

# Load template object
$template = new Template($registry);
$registry->set ('template', $template);

Because we want to use data from the model and controller in our templates, we will have to write a set() method to make variables available in the template. See the example below:

function set($varname, $value, $overwrite=false) {
        if (isset($this->vars[$varname]) == true AND $overwrite == false) {
                trigger_error ('Unable to set var `' . $varname . '`. Already set, and overwrite not allowed.', E_USER_NOTICE);
                return false;
        }

        $this->vars[$varname] = $value;
        return true;
}

function remove($varname) {
        unset($this->vars[$varname]);
        return true;
}

As you can see, the set() and remove() methods are fairly simple methods, used to set and remove a variable.

Now that we can set variables, all we need to write is the show() method, used for showing templates. The easiest way is to create a separate directory called 'templates', which holds all our template files, and then using an include() call to show a template. Of course your show() method can be completely different, and load the templates from the database or do something else. See the code snippet below for the show() method we'll be using:

function show($name) {
        $path = site_path . 'templates' . DIRSEP . $name . '.php';

        if (file_exists($path) == false) {
                trigger_error ('Template `' . $name . '` does not exist.', E_USER_NOTICE);
                return false;
        }

        // Load variables
        foreach ($this->vars as $key => $value) {
                $$key = $value;
        }

        include ($path);               
}

Our Template class is now complete, and can be used to display templates in the controller. For example, create a new file called 'index.php' in the 'templates' directory, and put the following code in it:

Hello from the View, echo $first_name; ?>!

Then, in the index controller (under controllers/index.php):

function index() {
        $this->registry['template']->set ('first_name', 'Dennis');
        $this->registry['template']->show('index');
}

If you now browse to our MVC system, you should get the following:

(Click here to view full version)

Now that we've got an active View component, our MVC system is complete, and can be used to create a full-blown website. But there are a few small things we have to take care of still.

Security Measures

At the moment all the sub-directories, such as 'controllers' and 'templates', are still publicly available to anyone who wants to visit it. This could mean that users start running controllers or templates that should only be run by our system, so let's block access to those directories.

With the .htaccess file this is really easy, and all it takes is the following command:

Deny from ALL

Put the above command in a new file called .htaccess, and save this file in the 'controllers' and 'templates' directory (and any other directory you want to protect). This will make sure that these directories are completely off limits for everyone.

Conclusion

In this tutorial I've shown you how to build a simple MVC system with PHP 5.1. Obviously there are many different ways of creating an MVC system, and the MVC system we built in this tutorial may not be the best way, but it does demonstrate the power that an MVC system brings.

You can click here to download the complete MVC system that we created in this tutorial.

If you have any questions or comments, please leave them below in the comments. Don't forget to join us at the PHPit Forums.

« Previous: The Controller



4 Responses to “Building a simple MVC system with PHP5”

  1. Marion DESNAULT Says:

    Hi,
    thanks for this useful article about the MVC system.
    Just to report a problem using function trim in the Router’s setPath method (line 14) under UNIX systems.
    If we give it an absolute path, it will delete the leading / and create problem when checking if this path is a directory.

  2. Solid Says:

    Why you haven’t used the magic overloading methods __set and __get, instead of using registry class? It’s more easy to use __set, __get with static propery, because in future you don’t need to use methods get()/set(). Anyway, I’m using something like you have been described here for compatibility with PHP4. Instead of class static property I’m using container function, because in PHP4 there are no chance to declare static property in class body.

  3. Alexander(Russia) Says:

    Hello, good article about the MVC for starting.

  4. Matthijs Says:

    Pretty cool article Dennis. Thanks. Good to see a relatively easy explanation of an MVC system. The thing with MVC is that the basics is fairly simple. But it can get complicated quickly when you throw in some locators, observers, datamappers and other classes and patterns.

Leave a Reply

About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.
Article Index
  1. Introduction & One Point of Entry
  2. Startup Tasks & Registry Class
  3. The Model & Router Class
  4. The Controller
  5. The View & Security Measures & Conclusion
Bookmark Article
Download Article
PDF
Download this article as a PDF file