PHP Framework Principles

Source: Internet
Author: User
Tags php framework php write smarty template zend framework

PHP Framework is now a very popular thing, many friends to develop applications and sites will choose a PHP framework or template, let's look at how the PHP framework is implemented.

This article mainly to talk about the framework theory, but not for any framework, but any framework can not be separated from this theory, first we understand the context of the framework, any technology appears to solve a problem, the previous blog has talked about Smarty, its existence is for HTML and PHP to better separate. The so-called "framework" is a way to unify the writing format, access to the self-restraint behavior, in fact, according to this argument each of us basically use their own definition of the framework, for example, before using the framework of their own development of a project, sometimes a day can not be completed, we to prevent confusion, In order to better remember that we will do directory planning and program planning, the subconscious of the program classification, put into different folders, so the framework came into being, and for example, we have done a CMS system, if we take over a similar project, you will repeat the code, the answer is certainly not, But if it is someone else's project you take to change is actually a very painful thing, because you do not know his this CMS rules is what, even their own projects for a long time if they do not have a fixed specification is also very easy to forget, then how to ensure that each time you write code can be in accordance with certain norms? , each project to use the things to pick out, directory structure to pick out, no matter what projects are written on this basis, then belong to their own framework is out.

But the framework is simply imperfect, so what should the framework be capable of, so we might as well think about what we would normally write code will do, what is the first thing to solve, in order to reduce the path problem, directory structure arrangement is actually very important, sometimes the file contains Moving files Again is always a very painful thing, the best way is, the absolute path, but there is a similar e:www such a problem, but this value can be obtained by pre-defined variable $_server["Document_root", we can define it as a constant, Define ("Root_path", $_server["Document_root"]), include Root_path. "/lib/mysql.php", like such a folder how to move will be nothing, then there is a fixed writing, in order to solve the problem of the path of writing, almost every page will be used, as well as the output of the template, database connection, then we can put these code together, or separate, each page contains can, the separated part is actually a small frame, why so, if we include them in, for example, Smarty template, is definitely instantiated good object, that the volume name is fixed, it may be $smarty if we include such a file in, This amount can not be used again, so that the following part of the code can not be used, because the containing class, such as the data class upload Class Image class Page class location has been written dead in this common file, in order not to change the code this directory is a must exist, directory format fixed, write code way constraints, This forms the framework.

Over the years the programmer's Summary of communication and development experience, we summed up some excellent way to write, the most classic is a single point of entry, what is a single point of entry, before we summed up some of the functions of almost every program to use, there are still some problems, such as the public file contains before we still do not know the root directory is how much , if we put a common file under each folder there is a code duplication problem, which day changes need to modify all, need to find out how many such files, it is now more than one program contains a program, and then the user access to N programs to complete the various functions, So the programmer would like to be able to reverse I use a program containing these different functions of the program, the user only access to this program can be, so the single point of entry mode appears, in the homepage of the site index.php write each program to use the part and then according to a certain amount, such as a get The amount to determine which program is currently being executed by index.php to include it in the run, which consists of a program. The way in which all functions are done, called a single point of entry, becomes a framework of the entry program and its corresponding directory structure.

For security in the inclusion of files often will be fixed directory, or it is easy to make a loophole so, often in the path of the tail and the limit. For example

The code is as follows Copy Code
<? Php
Include "./app/". $_get[' URL ']. ". PHP";
?>

The path can only be written like this index.php?url=news/list, actually contains the/app/news/list.php of course, the actual situation, but also to check whether the program files exist or something.

The whole point. We can write this entry file like this.

The code is as follows Copy Code

<?php

Write absolute path here

Write a database connection here

Here to write template initialization, configuration

The connection variables are judged here

This contains files coming in and running

Output template here

This closes the database.
?>

A process-oriented single-point entry framework is complete, is it not felt that each time in the address bar with a get inconvenient? Then we can change the wording, for example, the TP framework favorite with the http://localhost/index.php/news/list behind the/news/list by the program to the PHP path included in it. In the Apache environment, this/news/list can be obtained by the path_info of the server variable, if not. You can also use Request_uri to get close, IIS below, there are http_x_rewrite_url can get this value, since the single point of entry pattern appeared, and the OOP development mode from the beginning of the PHP5, the various OOP design framework let us dazzle, But original aim, is still what the entrance method, the path structure is what, the name of the filename of the rules, with what kind of access, you can run which program. The framework developed with OOP is nothing more than rewriting the main program into a class,
For example:

Include Common files, instantiate each class
Page-and initialization ();

Turn user-sent URLs into paths to include
page, processing network pull ();

This contains the program run
page, run ()

Output template
page, Output ()

A variety of frameworks just prepare a rule for us. In the process of our development accumulation, we often encapsulate some commonly used classes into classes, such as database classes, file upload classes, image processing classes, mail sending and receiving classes, remote access classes, various interface classes ... This time, we would like the framework to provide us with a good way to invoke the class, which is called "extensibility", such as the Db class of the TP framework. If you do not use their own class libraries only with their core framework, in fact, a few files are enough.
The TP framework supports three types of access formats.
/news/list
/index.php/news/list
/index.php?m=news&a=list
The first requires server Urlrewrite support, the following two kinds can be used directly,
In fact, the Zend framework also contains the same way as files. Contained in the form of a class, executed is actually:/Folder/object/method, this practice has the advantage. Because in the same function, a lot of similar code, encapsulated in the same class, you can more efficient reuse of code,

Like this.

The code is as follows Copy Code

Class Newsaction {
Public Function Head () {
Handle each page of the head here
}

Public Function index () {
$this->head ();
Work on this page here
}

Public function Show () {
$this->head ();
Work on this page here
}

You can also make use of constructors and so on, so that each function, when just came in the same thing done. The above is the theory of the simple framework.

How to make applications

index.php Main entry file

The code is as follows Copy Code
<?php
Define (' Isexist ', true);
Require "init.php";
$control = new Controller ();
$control, Run ();
?>

---------------------------------------------------------------------------------------------
init.php file

tr>
copy code
<?php
  if (!defined (' isexist '))
   exit ("Run program from the portal file");
  Header ("Content-type:text/html;charset=utf-8");
  
  if (!defined (' Root_path '))
  //Dynamic declaration here, ' is escape backslash, default ' is escape character
    Define (' Root_path ', Str_replace (', '/', dirname (__file__)));  
  require root_path. ' /a/config.php ';
  require Root_path. ' /a/controller.class.php ';
  require Root_path. ' /a/view.class.php ';
  require Root_path. ' /a/model.class.php ';
  
.

----------------------------------------------------------------------------------------------
config.php file

The code is as follows Copy Code
<?php
if (!defined (' isexist '))
Exit ("Please run the program from the portal file");
$C = Array (
' Url_mode ' =>1,//url mode, 1 for normal mode, 2 for Path_info mode
' Default ' = ' welcome ',//defaults to the controller
' Default_action ' = ' index '//default method
);
?>

-----------------------------------------------------------------------------------------------
controller.class.php file

The code is as follows Copy Code
<?php
Class Controller
{
Public Function Run ()
{
$this->analysis ();
The controller and method that begins parsing the URL to obtain the request
$control = $_get[' con '];
$action = $_get[' act '];
$action = Ucfirst ($action);
This constructs the path of the controller file.
$controlFile = Root_path. '/controllers/'. $control. '. class.php ';
if (!file_exists ($controlFile))//If the file does not exist with a hint error, the introduction
{
Exit ("{$control}.class.php controller does not exist <br>". "Please check:". $controlFile. " Whether there is <br> ");
}
Include ($controlFile);
$class = Ucfirst ($control); Capitalize the first letter of each word in the controller name as the class name of the controller
if (!class_exists ($class))//Determine if the class exists, if there is no prompt error
{
Exit ("{$control controller class not defined in}.class.php". $class);
}
$instance = new $class (); Otherwise, create an instance
if (!method_exists ($instance, $action))//Determine if the $action method exists in the instance $instance, the error is not present
{
Exit ("No method exists in the $class class:". $action);
}
$instance $action ();
}



protected function Analysis ()
{
$GLOBALS [' C '] [' url_mode '];
Global $C; Contains the global configuration array, which is defined in the config.ph file, and the global declaration $c is called by the external
if ($C [' url_mode '] = = 1)
If the URL pattern is 1 then get the controller in get, which means the URL address is this [url=http://localhost/index.php?c]http://localhost/index.php?c[/url]= controller &a= method
{
$control =!empty ($_get[' con ')? Trim ($_get[' con '): ';
$action =!empty ($_get[' act ')? Trim ($_get[' act '): ';
}
else if ($C [' url_mode '] = = 2)//If 2 then use Path_info mode, which is the URL address [url=http://localhost/index.php/]http://localhost /index.php/[/url] Controller/method/other parameters
{
if (Isset ($_server[' path_info '))
{
$_server[' path_info ']url The path information after the file name in the address, not good understanding, to see the example
For example, your current URL is [Url=http://www.php100.com/index.php]http://www.php100.com/index.php[/url] then your $_server[' PATH_INFO ' ] is empty.
But if the URL is [Url=http://www.php100.com/index.php/abc/123]http://www.php100.com/index.php/abc/123[/url]
Now the value of $_server[' Path_info ' will be the content after the index.php file name/abc/123/
$path = Trim ($_server[' path_info '), '/');
$paths = explode ('/', $path);
$control = Array_shift ($paths);
$action = Array_shift ($paths);
}
}
This determines whether the value of the controller is empty, and if it is empty, use the default
$_get[' con '] =!empty ($control)? $control: $C [' DEFAULT '];
Just like the top.
$_get[' act ' =!empty ($action)? $action: $C [' default_action '];
}
}
?>

--------------------------------------------------------------------------------------------------
welcome.class.php file

The code is as follows Copy Code
<?php
Class Welcome
{
function Index ()
{
Echo ' Welcome to use this CMS system ';
}
function Run ()
{
Echo ' Hello ';
}

function Show ()
{
Echo ' method name show ';
}
}
?>

PHP Framework Principles

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.