Php automatic loading-PHP namespace how to implement automatic loading

Source: Internet
Author: User
Tags autoload composer install web hosting
The namespace test is automatically loaded, but the two files I tested are not automatically loaded: {code ...} {code ...} error {code ...} modify index. php is changed to the following: Yes, but why cannot it be loaded automatically? {Code...} Test

Namespace is automatically loaded, but the two files I tested are not automatically loaded:

#/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

Modify index. php to the following: Yes, but why cannot 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 is automatically loaded, but the two files I tested are not automatically loaded:

#/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

Modify index. php to the following: Yes, but why cannot 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!
The reason is my suggestion!

PHP's earliest method to fetch the suite

When I was a beginner in PHP, one of the earliest problems was the difference between require and include?
What is require_once and include_once?
After understanding these issues, if you do not use the framework, you will often find code similar to this:

// Whatever. php // in this case, a similar require 'xxx _ class is required. php '; require 'yyy _ class. php '; require' zzz _ class. php ';//...

In other cases, the following occurs:

// Another. php // in this case, you need to use another kind of require 'yyy _ class. php'; require 'zzz _ class. php ';//...

As a result, there are at least two problems:
1. In many cases, the same class is used, so it is required to be written once in different places.
2. When there are more types, errors may occur when you forget to import them.

So why is it better to be cool?
When using a php script, the following types are added:

// 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';

In other cases, you can submit this case:

require 'load_everything.php'

As a result, a new problem arises: when there are many other types of web pages, a web page will be written into a bunch of code, how can this problem be solved?

_ Autoload

To solve this problem, PHP 5 began to provide the _ autoload function, a popular magic method.
When the class PHP you want to use cannot be found, it will inject the class alias into this function as a string, before the PHP fatal error surrender, perform the following sequence:

// 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}

It is also because PHP, the last "surrender" behavior, sometimes makes people not noticed confused: "How can my code run? I didn't have require at all... ", so I was labeled as" magic method 」.
In this case, the question seems to have been solved?
Unfortunately, there is still a small gap... that is, the content of this _ autoload function will become very huge. In the above example, we will go to the root object, the other_library resource, and the my_library resource. When I was sorting out the case, I had to be confused.

Spl_autoload_register

Since PHP starts from 5.1.2, one function is provided.
You can configure multiple autoload functions, and then start using them. The effect is the same as using _ autoload directly.
Now we can sort the differences for different purposes, and load them in batches.

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);}

The content of each loader can be changed a lot. You can make it more intelligent and perform string processing ....
The question of entering a category in an auto-scaling instance is finally solved ....

However, there are also 15 lines of code on the light, and there must be similar things in each project. Is there any way to generate these 15 lines?
My website is very simple. I tell you, I have my_library and other_library information, what kind of thing do you see on your own ...?
A No. If all the requests are written into the repository and the performance is not good, then you will try to use spl_autoload_register to remember everything ...?
I have to write 15 lines. I just want to write the following words:

$ Please_autoload = array ('My _ library ', 'other _ library ');
Can I invent a tool to eat the variable $ please_autoload, and then I want to write everything into it myself ...?

And so on. I have already installed the php program, and the JSON format in the web Hosting domain is even better. May I do this, OK?

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

Then, who will use a tool to generate a bunch of php programs related to autoload ..., Yes?

Yes.
Composer boarding
First, compile the composer (this article does not introduce how to secure it .)
Next, create a composer. json parser, which includes the following:

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

I typed more words than I expected, but it was similar.
Again, input

Composer install
After successful login, you will see a vendor resource containing an autoload. php file.
No, just as you did. You only need to merge into this case:

Require 'vendor/autoload. php ';
All the types you need will be automatically transferred in the initial and initial manner.
Php will no longer commit errors and say "You are not yet clarified!
Everything in the vendor is just a php code, and there is nothing special about it. You only need to check the original autoload. php code to know which php code composer has provided to you.

Category, and so on. My category is stored in my_library, and other_library is copied on the Internet. I want to use the Client class of Google API, Doctrine Resource class to manage the abstract class, And guzzlehttp's sending request class.
I tried to write down these cases, and then I was able to write about this resource. I didn't want to create the other_library resource manually. So powerful as composer... Why don't I manually renew my subscription? Yes?

Yes.
Check whether your software package is available in the "https://packagist.org/region" section.
Change composer. json of zookeeper to the following format:

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

Then the 'composer install' command not only automatically imports your class, but also automatically triggers the class you need, and then automatically enters them.
In this case, you can use require 'vendor/autoload. php. Composer is really great.

My blog
Http://blog.turn.tw /? P = 1039
Http://blog.turn.tw /? P = 1122

The namespace is not directly related to file loading,
Only some languages correspond the namespace structure to the file structure.
Taking php as an example,
The general namespace structure is mapped to the PHP file structure. The actual storage location of the class can be calculated by using the namespace name,
Then, during the instantiation, the set spl will be triggered to automatically load the function to introduce the file.

Portal
Https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md
Hope to help

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

The actual code execution isnew \DB\MySql();When this file is not found, your autoload function will be called andfile_exists("DB/MySql.class.php")Find the file in the current directory. If the file cannot be found, the error is displayed.

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.