Analysis of automatic loading of flight source code in PHP micro-frame

Source: Internet
Author: User
Tags autoload php class php framework stack trace
This article to share the content is about PHP micro-frame flight source automatic loading of the analysis, there is a certain reference value, the need for friends can refer to.

First look at the framework of the single-entry file index.php, first introduced the Flight.php framework class file.

<?phprequire ' flight/flight.php '; Flight::route ('/', function () {    echo ' Hello world! ';}); Flight::start ();

flight.php defines the Flight class, which defines 3 magic methods, three magic methods to prevent the current class from being instantiated

Don ' t allow object Instantiationprivate function __construct () {}private function __destruct () {}private function __clo NE () {}

If you try to go to new flight you will be prompted with the following error:

Fatal error:uncaught Error:call to Private flight::__construct () from invalid context in/usr/local/var/www/flight135/in Dex.php:3 Stack Trace: #0 {main} Next Error:call to Private flight::__destruct () from context ' IN/USR/LOCAL/VAR/WWW/FL Ight135/index.php:3 Stack Trace: #0 {main} thrown in/usr/local/var/www/flight135/index.php on line 3

Then an overloaded method __callstatic () is defined, and the __callstatic is called in the execution of Flight::route ('/', ' hello ') in index.php, where $name is ' route ', $ The params is the Hello function that you write yourself. Call the app () static method of the current class in __callstatic (), why not use Self::app () to invoke it?

/** * Handles calls to static methods. * * @param string $name method name * @param array $params method parameters * @return Mixed Callback results * @throws \e Xception */public static function __callstatic ($name, $params) {    $app = Flight::app ();    return \flight\core\dispatcher::invokemethod (Array ($app, $name), $params);}

Then it starts processing in the static app () to automatically load the

/** * @return \flight\engine Application instance */public static function app () {    static $initialized = false;    if (! $initialized) {        require_once __dir__. ' /autoload.php ';        Self:: $engine = new \flight\engine ();        $initialized = true;    }    Return self:: $engine;}

Into the autoload.php, introduced the core directory of the loader.php class file, loader is the loader.

Autoload.phprequire_once __dir__. ' /core/loader.php '; \flight\core\loader::autoload (True, DirName (__dir__));

Loader defines which types are loaded: $classes (an array of classpath), $instances (an array of objects), $dirs (an array of framework directory paths)

/** * Registered classes. * * @var array */protected $classes = Array ();/** * Class instances. * * @var array */protected $instances = Array ();/** * Autoload directories. * * @var array */protected static $dirs = Array ();

AutoLoad () uses Spl_autoload_register to register the LoadClass method in the current class (__class__) as a loaded execution method.

/** * Starts/stops autoloader. * * @param bool $enabled enable/disable autoloading * @param array $dirs Autoload directories */public static function aut Oload ($enabled = true, $dirs = Array ()) {    if ($enabled) {        spl_autoload_register (array (__class__, ' loadclass '));    }    else {        spl_autoload_unregister (array (__class__, ' loadclass '));    }    if (!empty ($dirs)) {        self::adddirectory ($dirs);}    } /** * autoloads classes.  * * @param string $class class name */public static function LoadClass ($class) {    $class _file = str_replace (Array (' \ \ \ '), ' _ '), '/', $class). PHP ';    foreach (self:: $dirs as $dir) {        $file = $dir. '/'. $class _file;        if (file_exists ($file)) {            require $file;            return;}}}    

Next we try to write a simple auto-load test according to the way flight automatically loads:

/autoload/index.php<?phpclass myclass{public static function __callstatic ($name, $params) {Self::app (); } public static function app () {require_once __dir__. '        /loader.php ';        Loader::autoload (True, DirName (__dir__));    New \autoload\test (); }}myclass::test (); new \autoload\test2 (); Var_dump (Loader::getclasses ());//array (2) {[0]=> string (*) "/usr/local /var/www/autoload/test.php "[1]=> string (PNS)"/usr/local/var/www/autoload/test2.php "}/autoload/loader.php<?    Phpclass Loader {public static $dirs = [];    public static $classes = []; public static function AutoLoad ($enabled =true, $dirs =[]) {if ($enabled) {Spl_autoload_register ([__clas        s__, ' loadclass ');        } else {spl_autoload_unregister ([__class__, ' loadclass ']);        } if (!empty ($dirs)) {self::adddirectory ($dirs); }} public static function LoadClass ($class) {$class _file = str_replace ([' \ \ ', ' _ '], '/', $class).                PHP ';                        foreach (self:: $dirs as $dir) {$file = $dir. '/'. $class _file;                if (file_exists ($file)) {require $file;                                Self:: $classes [] = $file;            Return            }}} public static function Adddirectory ($dir) {if (Is_array ($dir) | | | is_object ($DIR)) {            foreach ($dir as $value) {self::adddirectory ($value);        }} else if (is_string ($dir)) {if (!in_array ($dir, Self:: $dirs)) Self:: $dirs [] = $dir;    }} public static function Getclasses () {return self:: $classes; }}/autoload/test.php<?phpnamespace autoload;class Test {}/autoload/test2.php<?phpnamespace Autoload;class Test2 {}

X related recommendations:

Analysis of Goframe Framework's Gtime module and custom time format syntax

Analysis of Swoole and Swoft of Swoft source code

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.