PHP Framework Design ThinkPHP5 source code parsing one

Source: Internet
Author: User
Tags autoload php framework
Thinkphp is a fast, compatible and easy-to-use, lightweight, homegrown PHP development framework and the most widely used domestic framework in the country. Born in 2006, after FCS0.6.0 to thinkphp 0.9.5, after 1.0 to 3.0 development. 2015 released ThinkPHP5.0 version. With the new architecture idea, we introduced more PHP features, optimized the core, reduced the dependency, realized the real lazy loading, supported the composer, and made a lot of optimizations for API development, including the modules such as routing, log, exception, model, database, template engine, and authentication have been reconstructed. Compatible with the latest version of PHP. This makes him the preferred framework. The following also on its framework for a certain analysis.

Operating mechanism and process

1. Entry file index.php

Standalone mode

Define (' App_path ', __dir__. '/.. /application/');d efine (' App_debug ', true); Require __dir__. '/.. /thinkphp/start.php ';

Composer mode

Define (' App_path ', __dir__. '/.. /application/');d efine (' App_debug ', true); if (Is_file (__dir__. '/.. /vendor/autoload.php ') {    require_once __dir__. '/.. /vendor/autoload.php ';} else {    require __dir__. '/.. /thinkphp/start.php ';}

2. Frame Boot file start.php

namespace think;//thinkphp boot file//load base file require __dir__. '/base.php ';//Execute Application App::run ()->send ();

3. Global variable file base.php

Define (' think_version ', ' 5.0.2 '); TP version number define (' Think_start_time ', Microtime (true));//Start time define (' Think_start_mem ', Memory_get_usage ());//Get Assigned to PHP Memory Volume define (' EXT ', '. php '); File suffix define (' DS ', directory_separator);//system delimiter defined (' Think_path ') or define (' Think_path ', __dir__. DS);//project root directory define (' Lib_path ', Think_path. ' Library '. DS);//class Library Directory define (' Core_path ', Lib_path. ' Think '. DS);//core file directory define (' Trait_path ', Lib_path. ' Traits '. DS);//multiplexing mechanism file directory defined (' App_path ') or define (' App_path ', dirname ($_server[' script_filename ')). DS);//application root defined (' Root_path ') or define (' Root_path ', DirName (Realpath (App_path)). DS);//root directory defined (' Extend_path ') or define (' Extend_path ', Root_path. ' Extend '. DS);//extended directory defined (' Vendor_path ') or define (' Vendor_path ', Root_path. ' Vendor '. DS);//third-party libraries and plugins placed defined (' Runtime_path ') or define (' Runtime_path ', Root_path. ' Runtime '. DS);//Run cache directory defined (' Log_path ') or define (' Log_path ', Runtime_path. ' Log '. DS);//log file directory defined (' Cache_path ') or define (' Cache_paTH ', Runtime_path. ' Cache '. DS);//cache file directory defined (' Temp_path ') or define (' Temp_path ', Runtime_path. ' Temp '. DS);//Temp directory defined (' Conf_path ') or define (' Conf_path ', app_path); Configuration file directory defined (' Conf_ext ') or define (' Conf_ext ', EXT); Config file suffix defined (' env_prefix ') or define (' Env_prefix ', ' php_ ');  Configuration prefixes for Environment variables//Environment constants define (' Is_cli ', Php_sapi = = ' CLI '? true:false);d efine (' Is_win ', Strpos (Php_os, ' WIN ')!== false);// Load loader class require Core_path. ' loader.php ';//Load environment variable configuration file if (Is_file (Root_path. '. Env ') {$env = Parse_ini_file (Root_path. '. Env ', true);  foreach ($env as $key = + $val) {$name = Env_prefix. Strtoupper ($key), if (Is_array ($val)) {foreach ($val as $k = $v) {$item = $name. '_' . Strtoupper ($K); Putenv ("$item = $v"); }} else {putenv ("$name = $val");}}} Register Auto-load \think\loader::register ();//Registration error and exception handling mechanism \think\error::register ();//Load Convention profile \think\config::set (include Think_path. ' Convention '. EXT);

4. Auto Loader file loader.php

Loader.php is an auto-loading implementation file for the framework's class. You can use the AutoLoad () auto-block class, import () To manually load the class for the specified directory.
protected static $map = []; The system's class name maps the cache array, which is used in the following Addmap ()
protected static $load = []; The system loads a list of cached arrays, using the following autoload ()
protected static $namespace = []; The system's namespace cache array, which is used in the following addnamespace ()

private static $PREFIXLENGTHSPSR 4 = [];p rivate static $PREFIXDIRSPSR 4    = [];

The system's PSR-4 cache array, used in the following Registercomposerloader ()
private static $PREFIXESPSR 0 = []; The PSR-0 cache array for the system is used in the following Registercomposerloader ().

The above four static variables are used as an array of buffers for the loader to ensure load efficiency.

1 AutoLoad ($class)
Automatically loaded according to the class name.

public static function AutoLoad ($class) {}

Use class library mappings to load the corresponding classes.

if (Isset (self:: $map [$class])) {    if (Is_file (self:: $map [$class])} {        app_debug && self:: $load [] = self: : $map [$class];        Include self:: $map [$class];    }}

Using the composer Load class

ElseIf ($file = Self::findfileincomposer ($class)) {    app_debug && self:: $load [] = $file;    Include $file;}

Automatically load classes based on namespaces

else {    if (!strpos ($class, ' \ \ ')) {        return;    }    List ($name, $class) = explode (' \ \ ', $class, 2);        if (Isset (self:: $namespace [$name])) {        $path = self:: $namespace [$name];    } elseif (Is_dir (Extend_path. $name)) {        $path = Extend_path. $name. DS;    } else {        return;    }    $filename = $path. Str_replace (' \ \ ', DS, $class). EXT;        if (Is_file ($filename)) {        if (App_debug && is_win && false = = = Strpos (Realpath ($filename), $class. E XT) {            return;        }        App_debug && Self:: $load [] = $filename;        Include $filename;    } else {        Log::record (' autoloader error: '. $filename, ' notice ');}    }

2 Addmap ($class, $map = ")
Registering Class name Mappings
The public static function Addmap ($class, $map = ') {} array is merged into $map, and the string is associated to $class.

if (Is_array ($class)) {self    :: $map = Array_merge (self:: $map, $class);} else {self    :: $map [$class] = $map;}

3 AddNamespace ($namespace, $path)
Registering the Association of Namespaces and Paths
public static function AddNamespace ($namespace, $path = ') {} array is merged into $namespace, and the string is associated to path.

if (Is_array ($namespace)) {self    :: $namespace = Array_merge (self:: $namespace, $namespace);} else {    self::$ namespace[$namespace] = $path;}

4 Register ($autoload = ")
Registering the automatic loading mechanism
public static function Register ($autoload = ') {} think\loader::autoload () system automatically loaded
Self::registercomposerloader () composer automatic loading

Spl_autoload_register ($autoload $autoload: ' think\\loader::autoload '); Self::registercomposerloader ();

5 Composer Auto-loaded registration
private static function Registercomposerloader () {} about composer automatic loading mechanism see Basic principles of PHP composer automatically loaded

6 Composer Auto-loaded two private methods

private static function Composerrequire ($fileIdentifier, $file) {}private static function Findfileincomposer ($class, $ ext = '. php ') {}

7 Import ($class, $baseUrl = ", $ext =ext)
Manually loading the $class named $ext suffix file under $baseurl
public static function Import ($class, $baseUrl = ", $ext = ext) {} First analyzes $baseurl,
Then find the $baserurl. $class. $ext file name, and then load the corresponding file

The above is the PHP framework design ThinkPHP5 Source resolution one of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.