Build your own PHP Framework Experience (II)

Source: Internet
Author: User
Tags php framework phpinfo yii

Continuation of the statement

For this update, I would like to say:

    • This framework by I pick time to improve, and I am not a big god of PHP characters, so the framework is unavoidable, ask the great gods point out.
    • This framework of Knowledge point application will be written in the blog, we have any objection can be discussed together, but also hope to see the blog can learn them.
    • This update, updated the function specification of some problems, such as the function as far as possible to be independent, each function as far as possible to do one thing alone, to minimize the function of dependence. It also optimizes the overall framework, adding the SQ global class to handle global functions, variables.

Post the GitHub address again: Sqier frame GitHub Address

callback function

Replace the very low class name assembly instantiation, and then assemble the use of the 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();

Post-Modification Code

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

Here is a description of the PHP function callback application: Call_user_func and Call_user_func_array:

Call_user_func (Callback $function [, Mixed $parameter [, mixed $ ...])

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

Return value: Returns the result of the calling function, or false.

The usage of Call_user_func_array () is similar to that of Call_user_func, except that the passed parameter params is a whole array.

In addition, the Call_user_func series function can also pass in the first parameter to pass in the anonymous parameter, can be very convenient to callback some events, these features in the complex framework of the application is also very extensive, such as the Yii2 event mechanism of the use of callback function is based on this.

View Layer and OB functions

The framework defines the Render method in the controller's base class to render the page, which invokes the static function of the Class View to parse the template that loads the corresponding page.

public static function display($data, $view_file) {    if(is_array($data)) {        extract($data);//extract函数解析$data数组中的变量    }else {        //抛出变量类型异常    }    ob_start();    ob_implicit_flush(0);    include self::checkTemplate($view_file);//自定义checkTemplate函数,分析检查对应的函数模板,正常返回路径    $content = ob_get_clean();    echo $content;}

Here is the emphasis on the OB (output buffering) series functions, which refer to the function of the brief generation of magic OB:

    • Prevents the use of Setcookie after the browser has output, or errors caused by the Header,session_start function. In fact, this usage is less good, develop good code habits.
    • Capturing the output of some unreachable functions, such as phpinfo, will output a whole bunch of HTML, but we can't use a variable such as $info=phpinfo () to capture it, and the OB works.
    • Processing of output content, such as gzip compression, for example, for simple conversion, such as some string substitution.
    • Generating a static file is essentially capturing the output of the entire page and then saving it to a file that is often used in generating HTML or full-page caches.

After the Ob_start () function executes, the buffer is opened, the following output is loaded into the buffer of the system, the Ob_implicit_flush (0) function closes the absolute swipe (ECHO, etc.), and the contents of the buffer are finally taken out using the Ob_get_clean () function.

Class __url__ constants and global classes

TP in the __url__ and other global constants with very convenient, can be very simple to achieve jump and other operations, and define its function CreateURL function I want to reuse, and then draw on Yii's global class definition method:

Define the base class and the detailed method (the future global method will be written here)

class BaseSqier{    //方法根据传入的$info信息,和当前URL_MODE解析返回URL字符串    public static function createUrl($info = ‘‘) {        $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 directly in the global context. This makes it easy to define __url__ constants.

Define a database connection base class with a singleton pattern
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("连接数据库失败,请检查数据库配置信息!");        $link->query(‘set names utf8‘);    }    public function __clone() {        return self::getInstance();    }}

The core of using singleton mode is:

    • The privatization constructor makes it impossible to create an object with new, and also prevents subclasses from inheriting it and rewriting its constructors;
    • Holds the current object with a static variable, defines a static method to return an object, such as an object that has not yet been instantiated, instantiates one, deposits a static variable, and returns.
    • Construct its __clone magic method to prevent clone from a new object;
SQL query function for DB class

The DB query function is a very complex part, it is a self-made system of things, such as TP and Yii Query method has its unique place. For the time being, I borrowed the model base class of TP for a while, and then I can fill this up slowly.

Well, the trick of introducing a method in a query like TP is to return this return the processed query object at the end of each search method.

Subsequent

The mapping between the data table in the YII2 and the Model class property is cool (though it's been deep), and the module I've been avoiding before (module, I can imagine the trouble of parsing when adding it to the URI) has time to think about it.

Edge Write Edge optimization.

Well, to be continued ... By the way, advertise your personal station: www.alwayscoding.cn My contact information on the right side of the message board page, there is a problem where you can communicate.

Build your own PHP Framework Experience (II)

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.