PHP Automatic Loading-php namespace namespace how to implement automatic loading

Source: Internet
Author: User
Tags autoload composer install

Test

namespace will load automatically, but the two files I have tested are not loaded automatically:

#/DB/MySql.class.phpnamespace DB;class MySql{    public function __construct()    {        var_dump(__FILE__);    }}
#/index.phpnamespace Home;use DB\MySql;$mysql = new MySql();

Error

Fatal error: Class 'DB\MySql' not found in D:\localhost\demo\space\index.php on line 23

Modify

Change the index.php to the following, yes, but why can't it be loaded automatically?

phpnamespace Home;use DB\MySql;spl_autoload_register(function ($class) {    if ($class) {        $file = str_replace('\\', '/', $class);        $file .= '.class.php';        if (file_exists($file)) {            include $file;        }    }});$mysql = new MySql();

Reply content:

Test

namespace will load automatically, but the two files I have tested are not loaded automatically:

#/DB/MySql.class.phpnamespace DB;class MySql{    public function __construct()    {        var_dump(__FILE__);    }}
#/index.phpnamespace Home;use DB\MySql;$mysql = new MySql();

Error

Fatal error: Class 'DB\MySql' not found in D:\localhost\demo\space\index.php on line 23

Modify

Change the index.php to the following, yes, but why can't it be loaded automatically?

phpnamespace Home;use DB\MySql;spl_autoload_register(function ($class) {    if ($class) {        $file = str_replace('\\', '/', $class);        $file .= '.class.php';        if (file_exists($file)) {            include $file;        }    }});$mysql = new MySql();

Use composer!
Reason to hear me explain!

PHP's first way to read a suite

One of the first questions about PHP is require and include.
What is require_once and include_once?
Once you understand these questions, if you don't use the framework, you'll often get code like this:

// whatever.php// 這檔案需要用到幾個類別require 'xxx_class.php';require 'yyy_class.php';require 'zzz_class.php';// ...

And then, in the other files, we'll show you:

// another.php// 這檔案需要用到幾個類別require 'yyy_class.php';require 'zzz_class.php';// ...

This result will produce at least two questions:
1. Many files use the same class, which is required to be loaded in different places.
2. When the category is more, it will be very chaotic, forgetting to upload the error.

So, why not try a lazy lazy approach?
Write a PHP that is loaded into all categories:

// load_everything.phprequire 'xxx_class.php';require 'yyy_class.php';require 'zzz_class.php';require 'aaa_class.php';require 'bbb_class.php';require 'ccc_class.php';

And then load this file in the other files:

require 'load_everything.php'

The new question comes again: when there are a lot of other things, a Web page will load a bunch of code and eat memory.

__autoload

To understand this problem, PHP 5 begins by providing __autoload this "magic method" function.
When you want to use the type of PHP can not find, it will be the name of a string into this function, before the PHP spray error surrender, do the final try:

// autoload.phpfunction __autoload($classname) {    if ($classname === 'xxx.php'){        $filename = "./". $classname .".php";        include_once($filename);    } else if ($classname === 'yyy.php'){        $filename = "./other_library/". $classname .".php";        include_once($filename);    } else if ($classname === 'zzz.php'){        $filename = "./my_library/". $classname .".php";        include_once($filename);    }    // blah}

And because PHP is "the last attempt before surrender", it sometimes confuses people who are not aware of it. "Strange how My Code runs?" I have no require at all. "So called"magic method".
So, the question seems to be resolved?
Unfortunately, there is a small lack of, that is, this __autoload function will become very large. In the above example, we will go to the root of the record to find, will go to Other_library folder, will go to My_library folder to find. It was a bit confusing in the archives.

Spl_autoload_register

Since PHP started with 5.1.2, it provides a more functional function.
You can write more than one autoload function, and then register it with the same effect as the direct use of __autoload.
Now it can be used for different purposes, in batches autoload.

spl_autoload_register('my_library_loader');spl_autoload_register('other_library_loader');spl_autoload_register('basic_loader');function my_library_loader($classname) {    $filename = "./my_library/". $classname .".php";    include_once($filename);}function other_library_loader($classname) {    $filename = "./other_library/". $classname .".php";    include_once($filename);}function basic_loader($classname) {    $filename = "./". $classname .".php";    include_once($filename);}

Every loader can make a lot of changes. You can write more sentences to make it smarter, to be able to line the strings ....
The question of self-loading is finally resolved ....

But the code on the light also has 15 lines, and every project must write something similar. Is there any way to self-produce these 15 rows?
My wish is very simple, I tell you, anyway, I have My_library folder and Other_library folder, you go to see what kind of all loaded into good ...?
Ah right, all loaded into just said that the performance is not good, then you go to see what you all want to do with spl_autoload_register remember it good or not ...?
I lazy 15 lines, I just want to hit these words:

$please _autoload = Array (' my_library ', ' other_library ');
Is it possible to develop a tool to eat $please_autoload this change, and then you want to download everything ...?

Sunglass and so on, I even lazy PHP code to play, in the web domain JSON format is more simple. Allow me to fight like this, okay?

{    "autoload": [        "my_library",        "other_library"    ]}

And then who came up with a tool for me to produce a bunch of autoload PHP code ..., OK?

OK.
Composer Airport
First of all, install the composer (this article does not introduce how to install. )
Again, create a Composer.json file that will enter these:

{    "autoload": {        "classmap": [            "my_library",            "other_library"        ]    }}

More than the original hope of a dozen words, but almost.
Again, enter in the terminal

Composer Install
After the success, you'll see a vendor folder with a autoload.php inside it.
Yes, just like you dreamed. You just load this file:

Require ' vendor/autoload.php ';
All of the types you need will be automatically loaded in the appropriate way, at the proper time.
PHP will no longer spray the error saying that you "are not defining"!
Everything in this vendor folder is just PHP code, and there's no special magic. Just go to see Autoload.php's original code, you can know composer exactly wrote which PHP codes to you.

Sunglass and so on, I write the category are placed in the my_library, other_library are the Internet copy under the present category. I want to use the Google API's client category, the doctrine repository to manage the abstraction category, and the guzzlehttp of sending request classes.
I'm going to download these files, and then I'll drop them all lazy, and I don't even want to build other_library this folder. Composer really so God ... Why don't you just download it and help me download it? Can I?

OK.
Check out the names of the several kits in "https://packagist.org/" and the version you need.
Change the Composer.json to this:

{    "require": {        "google/apiclient": "1.0.*@beta",        "guzzlehttp/guzzle": "~4.0",        "doctrine/dbal": "~2.4"    },    "autoload": {        "classmap": [            "my_library"        ]    }}

Then the ' composer Install ' command, in addition to loading your own, will automatically download the kinds of things you need and then load them automatically.
Like require ' vendor/autoload.php '. Composer is really great.

My blog.
http://blog.turn.tw/?p=1039
http://blog.turn.tw/?p=1122

Namespaces are not directly related to file loading,
Just some languages, which correspond to the structure of the named spatial structure and the document.
In PHP, for example,
The general namespace structure, with the PHP file structure is a mapping relationship, through the name of the namespace, you can figure out the actual storage location of the class,
When instantiated, it triggers the introduction of the file with the set SPL auto-load function.

Transmission Door
Https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md
I hope we can help.

namespace Home;use DB\MySql;$mysql = new MySql();

The actual execution of the code is new \DB\MySql(); not found when the file will call your AutoLoad function and file_exists("DB/MySql.class.php") , in the current directory to find the file, in the case can not be found, and then you see the error

  • 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.