PHP (20140523) PHP for MVC development: a simple MVC

Source: Internet
Author: User

Today, I studied the structure of PHP MVC, so I decided to write a simple MVC so that I could enrich it later.
As for what MVC structure, is actually three model,contraller,view word abbreviation,, Model, the main task is to the database or other file system data according to the way we need to read out. View, mainly responsible for the page, the data in the form of HTML display to the user. Controller, mainly responsible for business logic, according to the user request for the allocation of requests, such as display login interface, you need to call a controller Usercontroller method loginaction to display.
Let's use PHP to create a simple MVC architecture system.
Start by creating a single point of entry, the bootstrap file index.php, as the only entry for the entire MVC system. What is a single point of entry? The so-called single-point entry is the entire application with only one entry, and all implementations are forwarded through this portal. Why do we have to do a single point of entry? There are several advantages to a single point entry: First, some system-wide variables, classes, and methods can be handled here. For example, you want to filter the data initially, you want to simulate session processing, you need to define some global variables, even if you want to register some objects or variables into the registrar. Second, the structure of the procedure is more clear and concise. Of course there are plenty of benefits. :)

<?php
Include ("core/ini.php");
Initializer::initialize ();
$router = loader::load ("router");
Dispatcher::d Ispatch ($router);

This document only has 4 sentences, we now have a sentence to analyze.
Include ("core/ini.php");

Let's see core/ini.php.

<?php
Set_include_path (Get_include_path (). Path_separator. "Core/main");
Set_include_path-sets the include_path configuration option
function __autoload ($object) {
Require_once ("{$object}.php");
}

This file first sets up the include_path, that is, if we want to find the included files, tell the system to look in this directory. In fact, we define the __autoload () method, this method is added in the PHP5, that is, when we instantiate a function, if this file does not, it will automatically load the file. The official explanation is:
Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is has to write a long list of needed includes at the beginning of each script (one for E Ach class).

In PHP 5, this is no longer necessary. You could define an __autoload function which was automatically called in case you were trying to use a class/interface which Hasn ' t been defined yet. By calling this function, the scripting engine is given a, chance to load, the class before PHP fails with an error.

Next, let's look at the following sentence
Initializer::initialize ();
This is called a static function of the initializer class initialize, because we set the include_path in ini.php, and defined __autoload, so the program will automatically core/ The main directory looks for initializer.php.
The initializer.php file is as follows:

<?php
Class initializer
{
public static function Initialize () {
Set_include_path (Get_include_path (). Path_separator. "Core/main");
Set_include_path (Get_include_path (). Path_separator. "Core/main/cache");
Set_include_path (Get_include_path (). Path_separator. "Core/helpers");
Set_include_path (Get_include_path (). Path_separator. "Core/libraries");
Set_include_path (Get_include_path (). Path_separator. "App/controllers");
Set_include_path (Get_include_path (). Path_separator. " App/models ");
Set_include_path (Get_include_path (). Path_separator. " App/views ");
Include_once ("core/config/config.php");
}
}
?>

This function is very simple, just define a static function, initialize function, this function is set include_path, so that later if the inclusion of files, or __autoload, will go to these directories to find.

OK, let's go on, look at the third sentence.
$router = loader::load ("router");

This sentence is also very simple, is loaded loader function static function load, below we come to loader.php

<?php
Class Loader
{
private static $loaded = Array ();
public static function Load ($object) {
$valid = Array ( "library",
"View",
"Model",
"Helper",
"Router",
"Config",
"Hook",
"Cache",
"DB");
if (!in_array ($object, $valid)) {
throw new Exception ("Not a valid object ' {$object} ' to load ');
}
if (Empty (self:: $loaded [$object])) {
Self:: $loaded [$object]= new $object ();
}
Return self:: $loaded [$object];
}
}

This file is to load the object, because later we may enrich this MVC system, there will be model,helper,config and so on components. If the loaded component is not in a valid range, we throw an exception. If so, we instantiate an object, which in fact uses a single-piece design pattern. That is, this object can only be an instantiated object, if not instantiated, create a, if present, do not instantiate.

OK, because we're going to load the router component now, so let's look at the router.php file, the function of which is to map the URL and parse the URL.
router.php

<?php
Class Router
{
Private $route;
Private $controller;
Private $action;
Private $params;
Public Function __construct ()
{
$path = Array_keys ($_get);
if (!isset ($path [0])) {
if (!empty ($default _controller))
$path [0] = $default _controller;
Else
$path [0] = "index";
}
$route = $path [0];
$this->route = $route;
$routeParts = Split ("/", $route);
$this->controller= $routeParts [0];
$this->action=isset ($routeParts [1])? $routeParts [1]: "Base";
Array_shift ($routeParts);
Array_shift ($routeParts);
$this->params= $routeParts;
}
Public Function getaction () {
if (Empty ($this->action)) $this->action= "main";
return $this->action;
}
Public Function Getcontroller () {
return $this->controller;
}
Public Function Getparams () {
return $this->params;
}
}

We can see that first we get the URL of $_get, the user request, and then we parse the Controller and action from the URL, and the params
For example, our address is HTTP://WWW.TINOWEB.CN/USER/PROFILE/ID/3.
So from the above address, we can get the controller is user,action seems to profile, parameter is ID as well as 3

OK, let's see the last sentence.
Dispatcher::d Ispatch ($router);

The meaning of this sentence is very clear, is to get the results of the URL parsing, and then through the dispatcher to distribute controlloer and action to response to the user
Okay, let's see the dispatcher.php file.

<?
Class Dispatcher
{
public static function Dispatch ($router)
{
Global $app;
Ob_start ();
$start = Microtime (true);
$controller = $router->getcontroller ();
$action = $router->getaction ();
$params = $router->getparams ();
$controllerfile = "app/controllers/{$controller}.php";
if (file_exists ($controllerfile)) {
Require_once ($controllerfile);
$app = new $controller ();
$app->setparams ($params);
$app $action ();
if (Isset ($start)) echo "

tota1l time for dispatching is: ". (Microtime (True)-$start). " Seconds.

";
$output = Ob_get_clean ();
Echo $output;
}else{
throw new Exception ("Controller not Found");
}
}
}

This class is obviously to get $router to find the Controller and action in the file in response to the user's request.

OK, we have a simple, MVC structure, so, of course, this is not a very complete MVC, because there is no view and model involved, I am rich here.

Let's write a controller file to test the system above.

We create a user.php file under app/controllers/

user.php
<?php
Class User
{
function Base ()
{
}
Public Function Login ()
{
echo ' Login HTML page ';
}
Public Function Register ()
{
echo ' register HTML page ';
}
Public Function SetParams ($params) {
Var_dump ($params);
}
}

You can then enter Http://localhost/index.php?user/register or Http://localhost/index.php?user/login in the browser to test it.

-From the Wind wave

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.