2. URL mapping and index.php

Created Tuesday 21 January 2014
http://www.nathandavison.com/article/10/custom-php-mvc-tutorial-part-2-url-mapping-and-indexphp

  1. .htaccess
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^([a-zA-Z]*)/?([a-zA-Z]*)?/?([a-zA-Z0-9]*)?/?$ index.php?controller=$1&action=$2&id=$3 [NC,L]

OR

Options +SymLinksIfOwnerMatch
RewriteEngine on
RewriteRule ^([a-zA-Z]*)/?([a-zA-Z]*)?/?([a-zA-Z0-9]*)?/?$ index.php?controller=$1&action=$2&id=$3 [NC,L]

  1. index.php
//require the general classes
require("classes/loader.php");
require("classes/basecontroller.php");
require("classes/basemodel.php");

//require the model classes
require("models/home.php");

//require the controller classes
require("controllers/home.php");

//create the controller and execute the action
$loader = new Loader($_GET);
$controller = $loader->CreateController();
$controller->ExecuteAction();

  1. loader.php
class Loader {
private $controller;
private $action;
private $urlvalues;

//store the URL values on object creation
public function __construct($urlvalues) {
$this->urlvalues = $urlvalues;
if ($this->urlvalues['controller'] == "") {
$this->controller = "home";
} else {
$this->controller = $this->urlvalues['controller'];
}
if ($this->urlvalues['action'] == "") {
$this->action = "index";
} else {
$this->action = $this->urlvalues['action'];
}
}

//establish the requested controller as an object
public function CreateController() {
//does the class exist?
if (class_exists($this->controller)) {
$parents = class_parents($this->controller);
//does the class extend the controller class?
if (in_array("BaseController",$parents)) {
//does the class contain the requested method?
    if (method_exists($this->controller,$this->action)) {
     return new $this->controller($this->action,$this->urlvalues);
    } else {
//bad method error
     return new Error("badUrl",$this->urlvalues);
    }
} else {
//bad controller error
    return new Error("badUrl",$this->urlvalues);
}
} else {
//bad controller error
return new Error("badUrl",$this->urlvalues);
}
}
}



Backlinks: