Search code examples
phpmodel-view-controllerfront-controller

PHP Front Controller with MVC


I am trying to delve into MVC with Front Controller Design.

I want to invoke my entire application by using one line, for example in index.php:

require_once(myclass.php);
$output = new myClass();

I would love to get rid of the require_once line, but I don't see how I could load my class without including it?

Anyway my main question would be how to load my various controllers and models and views etc using a one front end class. So far I have come up with:

class myClass
{
    private $name;
    public $root = $_SERVER['DOCUMENT_ROOT'];
    private $route = array("Controller" => "", "Model" => "", "View" => "", "Paremeters" => "");
    function __construct() 
    {   $uri = explode("/",$_SERVER['REQUEST_URI']);
        if(isset($uri[2])) {$this->route['Controller'] = $uri[2];}
        if(isset($uri[3])) {$this->route['Model'] = $uri[3];}
        if(isset($uri[4])) {$this->route['View'] = $uri[4];}
        if(isset($this->route['Controller'])) 
        {
            include($this->root."/".$this->route['Controller'].".php");
        }
    }

}

But it seems a bit convoluted and over the top. Also, once i've included the new class in the __construct, How am I supposed to load it?

Im sorry for the lack of knowledge, I have googled this a number of times and I keep coming up with the same pages that don't seem to expand my knowledge on the matter.


Solution

  • I'm surprised that in those two long and informative previous answers nobody bothered to actually answer your question in the simplest way.

    You want the __autoload() function. You'll still have to define it somewhere in your code, but it can simply be added to a global header file and then you don't have to explicitly write an include for every class definition.

    /* auto load model classes */
    function __autoload($class_name) {
            $filename = 'class.' . strtolower($class_name) . '.php';
            $file = __SITE_PATH . '/_model/' . $filename;
            if( file_exists($file) == false ) {
                    return false;
            }
            require($file);
    }