Build your own PHP Framework (2) and build a php Framework

Source: Internet
Author: User
Build your own PHP Framework (2) and build a php framework. Build your own PHP Framework (II), build a php framework, and continue with this update. I want to say that this framework has been well developed by myself, I am not a PHP guru. I have built my own PHP Framework (2) and built my php framework.
Statement

For this update, I want to say:

  • I have chosen time to complete this framework, but I am not a PHP guru. Therefore, framework vulnerabilities are inevitable.
  • The Knowledge Point application of this framework will be written in the blog. if you have any objection, you can discuss it together. you also hope that you can learn about it when you read the blog.
  • This update updates some functional specifications. for example, to make functions as independent as possible, each function should do only one thing separately and minimize function dependencies. We also optimized the overall framework and added the SQ global class to process global functions and variables.

Paste the GITHUB address again: the Sqier Framework GITHUB address

Callback function

Replaces the low class name assembly and instantiation, and then uses the assembly method name, using the PHP callback function method:

Original code:

$controller_name = 'Controller\\' . self::$c_name;$action_name = self::$a_name . 'Action';$controller = new $controller_name();$controller->$action_name();

Modified code

    $controller_name = 'Controller\\' . self::$c_name;    $controller = new $controller_name();    call_user_func([        $controller,        self::$a_name . 'Action'    ]);

The following describes how to use function callback in PHP: call_user_func and call_user_func_array:

Call_user_func (callback $ function [, mixed $ parameter [, mixed $...])

Call the user-defined function provided by the first parameter.

Return value: return the result of calling the function, or FALSE.

The usage of call_user_func_array () is similar to that of call_user_func, except that the input parameter params is an array.

In addition, the call_user_func series functions can pass in anonymous parameters in the first parameter to easily callback certain events. these features are also widely used in complex frameworks, for example, the use of callback functions in yii2's event mechanism is based on this.

VIEW layer and ob functions

The framework defines the render method in the controller base class to render the page. it calls the static function of the class VIEW to analyze and load the template of the corresponding page.

Public static function display ($ data, $ view_file) {if (is_array ($ data) {extract ($ data ); // The extract function parses the variable} else {// throw a variable type exception} ob_start (); ob_implicit_flush (0); include self: checkTemplate ($ view_file ); // customize the checkTemplate function. analyze and check the corresponding function template. the normal return path is $ content = ob_get_clean (); echo $ content ;}

Here we will focus on the ob (output buffering) series of functions, which will reference the role of the ob on behalf of magic:

  • Prevent the use of setcookie or header or session_start function after the browser outputs. In fact, it is better to use less and develop good code habits.
  • Capture the output of some unrecoverable functions. for example, phpinfo will output a lot of HTML, but we cannot use a variable such as $ info = phpinfo (); to capture, at this time, ob will work.
  • Process the output content, such as gzip compression, simple conversion, and replacement of some strings.
  • Generating static files is actually capturing the output of the entire page and saving it as a file, which is often used in generating HTML or the whole page cache.

After the ob_start () function is executed, it opens the buffer zone and loads the subsequent output content into the system buffer zone. the ob_implicit_flush (0) function closes the absolute sending (echo, etc ), finally, use the ob_get_clean () function to extract the buffer content.

Class/index. php/Article constant and global class

/Index in TP. global constants such as php and Article are easy to use and can easily implement jump and other operations. I want to reuse the createUrl function for defining it, so I will refer to YII's global class definition method:

Define the base class and detailed method (the Global method will be written here later)

Class BaseSqier {// method returns the URL string public static function createUrl ($ info = '') based on the incoming $ info information and the current URL_MODE resolution '') {$ url_info = explode ('/', strtolower ($ info); $ controller = isset ($ url_info [1])? $ Url_info [0]: strtolower (CONTROLLER); $ action = isset ($ url_info [1])? $ Url_info [1]: $ url_info [0]; switch (URL_MODE) {case URL_COMMON: return "/index. php? R = ". $ controller. '/'. $ action; case URL_REWRITE: return '/'. $ controller. '/'. $ action ;}}}

Define the class in the startup file and inherit the base class;

require_once SQ_PATH.'BaseSqier.php';class SQ extends BaseSqier{}

You can use the SQ: createUrl () method to create a URL. In this way, it is easy to define the/index. php/Article constant.

Define the database connection base class in Singleton mode
Class Db {protected static $ _ instance; public static function getInstance () {if (! (Self: $ _ instance instanceof self) {self: $ _ instance = new self ();} return self ::$ _ instance ;} private function _ construct () {$ link = new \ mysqli (DB_HOST, DB_USER, DB_PWD, DB_NAME) or die ("failed to connect to the database. Please check the database configuration information! "); $ Link-> query ('set names utf8');} public function _ clone () {return self: getInstance ();}}

The core of the Singleton mode is:

  • Privatized constructors make it impossible to use new to create objects, and prevent subclasses from inheriting them and rewriting their constructors;
  • Use static variables to store the current object and define static methods to return the object. for example, if the object has not been instantiated, instantiate one, store the static variable, and return the object.
  • Construct the _ clone magic method to prevent the clone of a new object;
DB-type SQL query functions

The DB query function is a complex part. it is a self-contained system, and the query methods such as TP and YII have their own uniqueness. I will borrow the MODEL base class of TP for the time being, and I will make up for it later.

Well, let's introduce the implementation of method join queries in queries like TP. The trick is that each join query method is used at the end.return thisTo return the processed query objects.

Follow-up

The ing between data tables and model class attributes in yii2 is cool (although it has been pitted), and modules that have been avoided before (module, I can imagine the trouble of parsing it when it is added to the URI) I have time to consider it.

Edge writing and optimization.

Well, to be continued... by the way, publicize your personal website: www.alwayscoding.cn my contact information on the right side of the message board page. if you have any questions, please contact me there.

Tips (II): Building a php Framework continued. for this update, I would like to say that this framework has been well developed by myself, but I am not a PHP guru...

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.