[Zz] php mvc development: A simple MVC

Source: Internet
Author: User
Tags autoload

I have studied the php mvc structure today, so I decided to write a simple MVC, so that I can enrich it later.
As for the MVC structure, there are actually three models, contraller, and view abbreviation, and model. The main task is to sort the data of databases or other file systems
Read it as needed. View, mainly responsible for page display data to users in HTML format. Controller, mainly responsible for business logic, according to the user's
Request for request allocation. For example, to display the login interface, you need to call the loginaction method of the controller usercontroller to display the request.
Next we will use PHP to create a simple MVC structure system.
Create a single point of entry, that is, index. php of the bootstrap file, as the only entry to the entire MVC system. What is a single point of access? The so-called single point of entry means that the entire application has only one

All implementations are forwarded through this portal. Why is single point of access required? The single point entry has several benefits: first, some variables, classes, and Methods processed globally by the system can be processed here.

For example, If You Want To preliminarily filter data and simulate session processing, you need to define some global variables, or even register some objects or variables into the register. Second, the program architecture is more
Clear and clear. Of course, there are many benefits. :)

<?php
include("core/ini.php");
initializer::initialize();
$router = loader::load("router");
dispatcher::dispatch($router);

There are only four sentences in this file. We will analyze the sentence now.
Include ("core/INI. php ");

Let's take a look at 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 include_path, that is, if we want to find the contained file, tell the system to find it in this directory. In fact, we define the _ autoload () method. This method is added in PhP5, that is, when we instantiate a function, if this file does not exist, 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
Having to write a long list of needed vertex des at the beginning of each
Script (one for each class ).

In PHP 5, this is no longer necessary. You may define an _ autoload
Function which is automatically called in case you are trying to use
Class/interface which hasn' t been defined yet. by calling this function
The scripting engine is given a last chance to load the class before PHP
Fails with an error.

Next let's take a look at the following sentence:
Initializer: Initialize ();
This is to call a static function initialize of the initializer class. PHP, set include_path and define _ autoload, so the program will automatically find initializer in the core/main directory. 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. It only defines a static function, initialize function. This function is used to set include_path. In this way, if a file or _ autoload is included in the future, it will be searched under these directories.

OK. Let's continue. See the third sentence.
$ Router = Loader: load ("Router ");

This sentence is also very simple, that is, loading the static function load of the loader function. Next we will use 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 used to load objects, because in the future we may enrich this MVC system, and there will be components such as model, helper, and config. If the loaded component is not valid

Within the range, we throw an exception. If so, we instantiate an object. In fact, the single-piece design mode is used here. That is, this object can only be an instantiated object. If it is not instantiated,
Create one. If yes, It is not instantiated.

Okay, because we want to load the router component now, let's take a look at the router. php file. The role of this file 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 $ _ get, the URL of the user request, and then parse the controller and action, and Params from the URL.
For example, our address is http://www.tinoweb.cn/user/profile/id/3
From the above address, we can get that the controller is user, the action seems to be profile, the parameter is ID and 3

OK. Let's take a look at the last sentence.
Dispatcher: Dispatch ($ router );

The meaning of this sentence is very clear, that is, get the URL resolution result, and then use dispatcher to distribute controlloer and action to response to the user
Okay. Let's take a look at 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 obvious, that is, get $ router to find the controller and action in the file to respond to the user's request.

OK, we have a simple MVC structure. Of course, it cannot be regarded as a complete MVC, because view and model are not involved yet. I will enrich them here when I have time.

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

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);
}
}

Then you can enter http: // localhost/index. php In the browser? User/register or http: // localhost/index. php? User/login to test.

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.