Principles of PHP framework templates-PHP source code

Source: Internet
Author: User
Tags smarty template
PHP framework is now a very popular thing. Many friends will choose a PHP framework or template for developing applications and websites. Let's take a look at how the PHP framework is implemented. PHP framework is now a very popular thing. Many friends will choose a PHP framework or template for developing applications and websites. Let's take a look at how the PHP framework is implemented.

Script ec (2); script

This article mainly talks about the framework theory, but does not target any framework. However, any framework is inseparable from this theory. First, we will understand the background of the framework, the emergence of any technology is to solve a problem. Previous blogs have talked about smarty, which exists in order to better separate html and php. The so-called "Framework" is a kind of self-restraint behavior to unify the writing format and access methods. In fact, according to this statement, each of us has basically used our own defined framework more or less, for example, if you develop a project by yourself before using the framework, sometimes it cannot be completed in a day. To prevent confusion, we plan directories and programs to better remember them, the framework came into being because of the subconscious classification of programs into different folders. For example, we once made a CMS system. If we took over another similar project, are you sure you want to repeat the code? The answer is definitely not. But if it's someone else's project, it's really a headache, because you don't know what the CMS rules are, even if your project has been running for a long time and you don't have a fixed specification, it's easy to forget, so how can we ensure that every time we write code, we can follow certain specifications to pick out the items used by each project and the directory structure, in the future, no matter what projects are written on this basis, your own framework will come out.

However, the framework is not perfect, so what capabilities should the Framework have? Instead, let's think about what the code we will write at ordinary times will do, what is the first solution? In order to reduce the path problem, the arrangement of the directory structure is actually very important. Sometimes it is always a headache to move files after file inclusion, what is the best solution? absolute path, but there is a problem like E: www at the same time, but this value can be obtained through the predefined variable $ _ SERVER ["DOCUMENT_ROOT"]. We can define it as a constant, define ("ROOT_PATH ", $ _ SERVER ["DOCUMENT_ROOT"]); include ROOT_PATH. "/lib/mysql. php "; there is no problem in how folders like this can be moved, so there is a fixed writing method. To solve the path problem, almost every page will be used, there is also the template output and database connection, so we can encapsulate the code, or separate it, each page can be included, divided These parts are actually a small framework. Why do we say this? If we include them, such as the smarty template, it must be an instantiated object, and the volume name is fixed, it may be $ smarty. If we include such a file, this quantity cannot be assigned again, so that the following code cannot be used, for example, if the position of the paging class of the Data upload class image class has been written to this public file, the directory must exist without modifying the code. The directory format is fixed, write code constraints, which forms a framework.

Over the years, programmers have summarized their experiences in communication and development and summarized some excellent writing methods. The most typical one is single point portal. What is single point portal, we have summarized some functions that almost every program uses. There are still some problems here. For example, we still don't know what the root directory is before the public file contains, if we put a public file under each folder and there is a code duplication problem, we need to modify all the files in one day and find the number of such files, now there are multiple programs that contain one program, and then the user can access n programs to complete various functions. So the programmer wants to wonder if I can use a program that contains these different functions, the user can only access this program, so the single point of entry mode appears, in the index of the home page of the website. in php, write the part used by each program and then follow the data volume. For example, a get volume is used to determine which program is actually to be executed, which is determined by the index. php includes it for running, which is a program. The method to complete all functions is called a single point of entry. Therefore, this entry program and its corresponding directory structure form a framework.

For security reasons, directories are often fixed when files are contained. Otherwise, vulnerabilities may easily occur. Therefore, a restriction is often imposed at the beginning and end of the path. For example

The Code is as follows:
Include "./app/". $ _ GET ['url']. ". php ";
?>

Then the path can only be written as index. php like this? Url = news/list, which actually contains/app/news/list. php. Check whether the program file exists.

Complete. We can write this entry file in this way.

The Code is as follows:

// Write the absolute path here

// Write the database connection here

// Write template initialization and configuration here

// Determine the connection variable here

// Include the file to run

// Output the template here

// Close the database here
?>

A process-oriented Single Point portal framework is complete. Do you think it is inconvenient to add a get in the address bar every time? We can change the writing method, for example, http: // localhost/index, which is the most popular in the tp framework. the/news/list after php/news/list is converted from the program to the php path. 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 obtain the approximate value. In IIS, there is HTTP_X_REWRITE_URL to obtain this value. Since the emergence of the single point of entry mode, the oop development mode has become popular since php5, we are dazzled by various oop design frameworks. However, what is the entrance method, what is the path structure, naming rules for file names, and what access methods are used, which program can be run. The framework developed with oop almost changes the main program into a class,
For example:

// Contains shared files and instantiates various classes.
Page-> initialization ();

// Convert the URL sent by the user to the path to be included
Page-> handle network pull ();

// Include the program running
Page-> Run ()

// Output Template
Page> output ()

All kinds of frameworks are just a rule for us .. During our development process, we often encapsulate some common classes into classes, such as database, file upload, image processing, email sending and receiving, and remote hosts, various interface classes ...... At this time, we hope that the framework can provide us with a better method to call classes, that is, the so-called "scalability", such as the Db class of the TP framework. If you don't use their own class libraries to use only their core framework, several files are enough.
The TP framework supports three access formats.
/News/list
/Index. php/news/list
/Index. php? M = news & a = list
The first type requires support for urlrewrite on the server, and the latter two types can be used directly,
In fact, the Zend framework is similar to the file inclusion method. It is included in the form of a class and actually executed as:/folder/Object/method. This method has advantages. Because there are many similar codes in the same function and they are encapsulated in the same class, code can be reused more efficiently,

For example

The Code is as follows:

Class NewsAction {
Public function head (){
Process the header of each page here
}

Public function index (){
$ This-> head ();
Process this page here
}

Public function show (){
$ This-> head ();
Process this page here
}

You can also use constructor to make every function do the same thing when it comes in. The above is the theory of a simple framework.

How to create an application

Index. php main portal File

The Code is as follows:
Define ('isexist', true );
Require "init. php ";
$ Control = new Controller ();
$ Control-> Run ();
?>

Bytes ---------------------------------------------------------------------------------------------
Init. php file

The Code is as follows:
If (! Defined ('isexist '))
Exit ("run the program from the entry file ");
Header ("Content-Type: text/html; charset = UTF-8 ");

If (! Defined ('root _ path '))
// Here, the dynamic declaration, ''is the escape backslash, default'' is the 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 ';

?>

Bytes ----------------------------------------------------------------------------------------------
Config. php file

The Code is as follows:
If (! Defined ('isexist '))
Exit ("run the program from the entry file ");
$ C = array (
'Url _ mode' => 1, // url mode. 1 indicates normal MODE, and 2 indicates path_info MODE.
'Default' => 'Welcome ', // DEFAULT Controller
'Default _ action' => 'index' // DEFAULT method
);
?>

Bytes -----------------------------------------------------------------------------------------------
Controller. class. php file

The Code is as follows:
Class Controller
{
Public function Run ()
{
$ This-> Analysis ();
// Start to parse the URL to obtain the request controller and Method
$ Control = $ _ GET ['Con '];
$ Action = $ _ GET ['ac'];
$ Action = ucfirst ($ action );
// Construct the path of the controller File
$ ControlFile = ROOT_PATH. '/Controllers/'. $ control. '. class. php ';
If (! File_exists ($ controlFile) // if the file does not exist, an error is prompted. Otherwise
{
Exit ("{$ control}. class. php controller does not exist
"." Check whether ". $ controlFile." exists.
");
}
Include ($ controlFile );
$ Class = ucfirst ($ control); // capital the first letter of each word in the Controller name as the class name of the controller.
If (! Class_exists ($ class) // determines whether the class exists. If no, an error is returned.
{
Exit ("Controller class not defined in {$ control}. class. php". $ class );
}
$ Instance = new $ class (); // otherwise, create an instance.
If (! Method_exists ($ instance, $ action) // checks whether the $ action method exists in the instance $ instance. If the $ action method does not exist, an error is prompted.
{
Exit ("$ class does not have a method:". $ 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. The global declaration $ C calls the external
If ($ C ['url _ mode'] = 1)
// If the URL mode is 1, GET the Controller in GET, that is, the url address is [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 ['ac'])? Trim ($ _ GET ['ac']): '';
}
Else if ($ C ['url _ mode'] = 2) // if it is 2, The PATH_INFO MODE is used, that is, the URL address is like this [url = http: // localhost/index. php/] http: // localhost/index. php/[/url] Controller/method/other parameters
{
If (isset ($ _ SERVER ['path _ info'])
{
// $ _ SERVER ['path _ info'] The PATH after the file name in the URL address. It is hard to understand. Let's take a look at the example.
// For example, if your current URL is [url = http://www.php100.com/index.php#http://www.php100.com/index.php#/url], your $ _ SERVER ['path _ info'] is blank.
// However, if the URL is [url = Response
// The current $ _ SERVER ['path _ info'] value 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 );
}
}
// Check whether the Controller value is null. If it is null, use the default value.
$ _ GET ['Con '] =! Empty ($ control )? $ Control: $ C ['default'];
// Same as above
$ _ GET ['ac'] =! Empty ($ action )? $ Action: $ C ['default _ action'];
}
}
?>

Bytes --------------------------------------------------------------------------------------------------
Welcome. class. php file

The Code is as follows:
Class Welcome
{
Function Index ()
{
Echo 'Welcome to this CMS system ';
}
Function Run ()
{
Echo 'hello ';
}

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

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.