A brief analysis of PHP development framework

Source: Internet
Author: User
Tags php framework

Definition of the development framework I did not find a very accurate description, the following statements basically summarize the development framework of the function and purpose

    • A framework is a semi-finished product of an application;
    • The frame is like a human skeleton;
    • A framework is a reusable set of components;
    • The framework is a reusable design component ...

In short, a framework is a set of norms or rules (ideas) that people (programmers) work under that specification or rule (thought). Or just use someone else's stage, and you'll do the show.

What are the advantages and disadvantages of PHP development framework

Advantages: As mentioned above, the framework is actually someone else to encapsulate some basic code into a library, let the programmer to invoke, such as form validation, file upload, verification code and other basic functions; So programmers only need to follow the framework of the method to write their own core code, the program can be basically formed. Therefore, the application of PHP framework can enable programmers to focus on the core code of the application, the basic code can directly invoke the framework of the class library, and the framework of the design structure can guarantee the team development code consistency, so can greatly improve the efficiency of web application development.

Cons: Nothing in this world is perfect, so there are pros and cons to using frame frame development. The disadvantage of PHP framework is that it encapsulates the basic functions of PHP, and for a novice PHP, he may not need to learn any basic PHP functions, just by flipping through the framework of the documentation and call the framework to encapsulate the interface to complete a full PHP application, In some ways this can reduce the technical requirements of PHP application development, but this is detrimental to learning, and eventually leads to too much reliance on the development framework. In a forum to see such a remark comments PHP development framework:

The person who
learns is born, and the man who uses it dies
MVC architecture What is the MVC architecture

MVC is a software architecture model in software engineering, and MVC divides software systems into three basic parts: model, view, and controller.

the Model data model is used to encapsulate data related to the business logic of the application and how to handle the data. "Model" has the right to direct data access, such as access to the database. "Model" does not depend on "view" and "Controller", that is, the model does not care how it will be displayed or how it is manipulated. However, changes in the data in the model are generally advertised through a refresh mechanism. To implement this mechanism, the views that are used to monitor this model must be registered in advance on this model, so that the view can understand the changes that have occurred on the data model.

The view view layer is capable of achieving a purposeful display of data (in theory, this is not required). There is generally no logic on the program in the view. To implement the Refresh feature on the view, the view needs to access the data model it monitors, so it should be registered with the data it is monitoring beforehand.

Controller controllers play an organizational role across different levels to control the flow of applications. It handles the event and responds. An "event" includes the user's behavior and changes on the data model.

Application of MVC architecture in Web development

MVC is widely used in Web applications, and the image on the right is an MVC-based Web request processing process.

First, the user sends a request to the controller, the controller sends the data demand to the data model according to the request of the user, and the data model is processed according to the demand (such as accessing the database, making the corresponding calculation, etc.), and the data result is returned to the controller. Once the controller gets the data, it can call the view, generate a page, and return it to the user.

Develop a simple PHP framework

Above said so much, the following we develop a simple PHP framework program, the framework sounds like a very complex, in fact, it is very simple, as long as the idea of understanding it is not a problem. The name of our frame is called small-framework.

A rough analysis of the processing process for user requests

We know that PHP initializes all of the resources each time it receives the request, and then releases all the resources after processing, and so is the PHP framework. After the framework receives the user's request, it needs an initialization process, instantiates the core module of the framework at initialization, and then processes the request to the appropriate module for the framework. Because it is not possible for all requests to use the same controller, unless the program function is very simple, we also need to invoke the corresponding controller according to the user's request after initialization, so we need a dispatcher (Dispatcher) to distribute the user's request. In the controller, we can invoke the data model and view to process the user's request.

Detailed analysis of the processing process of user requests

The above is a rough analysis of the user request processing process, the following more detailed analysis

From the above analysis, it is known that to process a user's request, the core modules of the framework, such as the dispatcher module, need to be initialized first, so the user's request needs to be redirected to an initialization page first, and redirects can Using the. htaccess file to implement, in our framework, we first redirect all requests to index.php, in the index.php to complete the initialization operation: the initialization of the core module, we can also read into the framework during initialization of the configuration file information, The call dispatcher then distributes the request to the appropriate controller, instantiates the controller, and invokes the method in the controller to process the user's request. In the controller, we can get the user's input, judge the user's request, and then call the corresponding data model to data processing, the controller to get the data, the data to the view, the view according to the resulting data return a page to the user, the request is over.

File structure of the framework

Based on the above analysis, we can list the file structure of Small-framework

    • Core modules of the Core/framework

    • dispatcher.php

    • controller.php
    • model.php
    • view.php

    • controller/a custom Controller

    • view/a custom view
    • model/a custom data model
    • Single entry for index.php frame
    • Configuration file for the config.php framework
    • . htaccess Redirect request to index.php
Start coding

With the above analysis, the basic process of the framework work is basically clear, we will start coding according to the Order of processing requested

First is the. htaccess file,

<ifmodule mod_rewrite.c>    rewriteengine    on/small-framework                  #  Framework-based root directory redirection    rewritecond%{request_filename}!-f    # If the user is not requesting a file    Rewritecond %{request_filename}!-d   # If the user is not requesting a directory    rewriterule. index.php [L]                       #  Redirect to index.php</IfModule>

Now if the user is not requesting js,css or a static file such as a picture, the user's request will be redirected to index.php, below we write index.php

Define Str_replace (' \ ', '/', DirName (__file__)));//define root directory/* Load core module */require root_path.' /config.php ';//main settings require root_path.' /core/dispatcher.php ';//distributor Module $DPT = new Dispatcher ();//Instantiate the request dispatcher $return _status = $dpt->run (); Echo $return _ Status;exit (0);

 

The user's request is routed to the dispatcher after the framework has been initialized, and the dispatcher actually determines the basis for the user's request distribution, and we can determine the controller based on the URI fragment, such as user request HTTP://WWW.EXAMPLE.COM/AAA/BBB, Then the dispatcher thinks it needs to call the controller AAA inside the BBB method to handle the user request, or by querying the string, for example, to request HTTP://WWW.EXAMPLE.COM?CONTROLLER=AAA&METHOD=BBB, The dispatcher knows the need to invoke the BBB method inside the AAA controller. In our small-framework, we distribute the request in the form of a URI fragment. The code for the dispenser is as follows:

classDispatcher {Private $path;  Public function__construct () {//gets the URI of the user request when instantiating the dispatcher        $this->path =$_server[' Path_info ']; }     Public functionrun () {//parse the URI to get the appropriate controller and method        $this->path =Trim($this->path, '/'); $paths=Explode(‘/‘,$this-path); //get the Controller class name and method name        $control=Array_shift($paths); $method=Array_shift($paths); //if the controller class name and method name are empty, the default is "index"        if($control= = ")$control= ' Index '; if($method= = ")$method= ' Index '; //get the file path of the controller class according to the framework's file structure        $control _file_name= Root_path. ' /controller/'.$control.‘. Php; if(file_exists($control _file_name))        {            include_once($control _file_name); $controller _name=$control.‘ _controller '; if(class_exists($controller _name))            {                //instantiating a controller                $control=New $controller _name(); if(method_exists($controller _name,$method))                {                    //if the method requested by the user exists, the call to the                    $control-$method(); returnok_200; }                Else returnError_404 ';        } else return error_404;    } else return error_404; }};

 

The dispatcher $contorl->$method() calls the controller method specified by the request, and now we can experiment with creating a aaa.php under controller/that declares a class named Aaa_controller and a method named BBB with access to public. You can [你的测试地址]/aaa/bbb access the controller by going to it.

Now our small-framework is not actually called a framework, because it does not yet define some basic operations, such as invoking data models, views, etc., which we define in controller.php, model.php, and core/under the In view.php, user-defined controllers, models, and views need to inherit from these three parent classes. We need to load the three parent class in index.php.

In index.php, in addition to loading the core module, we also loaded the user's own written model, controller and view needs to inherit the parent class, in the parent class we need to define some framework basic operations for the user to call

/**/require root_path. ' /core/controller.php '; /*  */require root_path. ' /core/model.php '; /*  */require root_path. ' /core/view.php ';

 

The first is controller.php, we instantiate the view by default when the controller is instantiated, the user can directly use the function in the view, and of course let the user load the view manually. The code is as follows

classcontroller{protected $view=NULL; protected $model=NULL;  Public function__construct () {//Instantiate the view when the controller is instantiated by default        $this->view =NewView (); }    //the user manually loads the corresponding model via Model_name    protected functionLoad_model ($model _name)    {        $model _file_name= Root_path. ' /model/'.$model _name.‘. Php; require_once($model _file_name); $this->model =New $model _name(); }};

 

In view we define the show method, where the parameters of the Show method are the view file name and the data passed to the view files, and the user can call the Show method in the controller to output the specified view

classview{ Public functionShow$view _file,$data=Array())    {        $view _file_name= Root_path. ' /view/'.$view _file.‘. Php; if(!file_exists($view _file_name))return FALSE; //Expand the array, the key name to do the variable name, the key value to do the variable value        Extract($data); //introducing the View file        include($view _file_name); return TRUE; }};

 

In model.php we can encapsulate some database queries and filter the SQL statements before all queries to ensure the security of the database.

classmodel{//Database Connection    protected $link=NULL;  Public function__construct () {$this->link =mysql_connect(Mysql_host, Mysql_user,Mysql_pass); mysql_select_db(mysql_db,$this-link); mysql_query("SET NAMES".)mysql_charset); }    /** Check Input SQL statements, filter sensitive characters*/    Private function_check ($sql)    {        /*Add a filter to $sql here*/        return $sql; }    /** Execute SQL command, successfully return result set and true, fail return false*/    protected functionQuery$sql)    {        return mysql_query($this->_check ($sql)); }    /** Execute SQL query, return result array, query failed return false*/    protected functionFetch_array ($sql)    {        $res=$this->query ($sql); return Mysql_fetch_array($res); }    /** Additional data processing operations can also be added*/};

By now, our small-framework is basically complete, small-frame is very simple, but as the learning software of the MVC Architecture and PHP framework should be enough to get started, And the other large PHP framework (where large is relative to small-framework) works in Small-framework is also very similar, the large-scale framework of the dispatcher set more reasonable, there will be a lot of use of the class library for users to call, If you have time, it is recommended to look at the source code of the large framework, learn the ideas, and there are many code optimizations in the large framework to learn.

(Turn) PHP Development Framework Analysis

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.