Write your own PHP MVC Framework [part 1]

6:47 PM Unknown 5 Comments


Abstract

This article shows you how to start writing your own php mvc framework ,from the basic architecture to an advanced approach to build more module in your framework.Am sharing with you this method ,in the hope that it will be useful.
"Unless you try to do something beyond what you have already mastered, you will never grow.                                                                                                         -Waldo Emerson

1.What is MVC ?!         

MVC is a software architecture - the structure of the system - that separates domain/application/business (whatever you prefer) logic from the rest of the user interface. It does this by separating the application into three parts: the model, the view, and the controller. 

  •  The model manages fundamental behaviors and data of the application. It can respond to requests for information, respond to instructions to change the state of its information, and even to notify observers in event-driven systems when information changes. This could be a database, or any number of data structures or storage systems. In short, it is the data and data-management of the application. 
  •  The view effectively provides the user interface element of the application. It'll render data from the model into a form that is suitable for the user interface. 
  •  The controller receives user input and makes calls to model objects and the view to perform appropriate actions. All in all, these three components work together to create the three basic components of MVC.
For more information visit this link :introduction to the mvc_framework

2.Architecture

The architecture is a combination of a front controller on the server and model-view-controller design pattern and a directory structure ,that makes adding features in a self contained modular way easy. We will delve into each of these core architectural components in turn below.
Directory structure


3.Configure Apache


sudo a2enmod rewrite

For and change AllowOverride None to AllowOverride All. This may be on lines 7 and 11 of /etc/apache2/sites-available/default. Modern versions of Ubuntu store these in the main config file: /etc/apache2/apache2.conf.

sudo nano /etc/apache2/apache2.conf

Now restart your apache server :

sudo service apache2 restart



4.The front controller: index.php

The first key point is that all site traffic is directed through index.php. This is a common design pattern called the front controller which allows us to load components used by the whole application such as user sessions and database connection in one place. We use mod_rewrite to make the URL look clean, converting:
myframework/user/login
to:
myframework/index.php?q=user/login

index.php then fetches the property q with $_GET['q']. using q as a command to tell the application what to do.


5.Build it


Start by creating a folder in your LAMP server /var/www directory lets call it framework Create a new file called .htaccess and open it in your favourite code editor, copy and paste the following code into the .htaccess file:
 .htaccess:


# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Set the default handler.
DirectoryIndex index.php

# Various rewrite rules.

  RewriteEngine on
  # Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]



This script tells Apache that whenever a HTTP request arrives and if no physical file (!-f) or path (!-d) or symbolic link (!-l) can be found, it should transfer control to index.php, which is the front controller. Next create a new file called index.php, to illustrate what the .htaccess file does add the following two lines to index.php.

<?php

echo "q=".$_GET['q'];
?>
Next: navigate to http://localhost/framework/stories/list.json in your browser and you should see the following:
q=stories/list.json

As you can see the stories/list.json part has been passed to index.php as a string rather than navigating to an actual folder and file location.

1) Decoding the route

Next we want to decode the "stories/list.json" so that we can use it in our application, in this example: 


  • stories is the controller (the module we want to use) 
  • list is the action 
  • json is the format

Copy and paste the following into index.php:

<?php

require "route.php";
$route = new Route($_GET['q']);

echo "The requested controller is: ".$route->controller."<br>";
echo "The requested action is: ".$route->action."<br>";
echo "The requested format is: ".$route->format."<br>";



and create a file called route.php with the following:

<?php

class Route
{
    public $controller = '';
    public $action = '';
    public $subaction = '';
    public $format = "html"; 

    public function __construct($q)
    {
        $this->decode($q);
    }

    public function decode($q)
    {
        // filter out all except a-z and / .
        $q = preg_replace('/[^.\/A-Za-z0-9]/', '', $q);

        // Split by /
        $args = preg_split('/[\/]/', $q);

        // get format (part of last argument after . i.e view.json)
        $lastarg = sizeof($args) - 1;
        $lastarg_split = preg_split('/[.]/', $args[$lastarg]);
        if (count($lastarg_split) > 1) { $this->format = $lastarg_split[1]; }
        $args[$lastarg] = $lastarg_split[0];

        if (count($args) > 0) { $this->controller = $args[0]; }
        if (count($args) > 1) { $this->action = $args[1]; }
        if (count($args) > 2) { $this->subaction = $args[2]; }
    }
}


Navigate again to http://localhost/framework/stories/list.json in your browser and you should see the following:

The requested controller is: stories
The requested action is: list
The requested format is: json


For more information visit this documentation  of the community  src:_Link_
note:this framework have inspired me to build my own framework .
@emoncms