PHP class autoload

I have a "simple structure" whose main instance is $ app. Now, what is the best way to implement an autoloader (without using Composer). I need a class that handles all autoload (supporting various namespaces). I have several approaches / dilemmas.

At first it seemed to me that I should create a โ€œstaticโ€ class that handles everything. But then something crossed my mind. If I use the autoloader before creating the $ app (which contains all the paths), I will need to determine the paths outside of the $ app. And also, if an error occurs during startup of the class, I could not correctly handle the error (the error handler is inside the $ app and is created after it).

Then I thought about dependency injection, making the autoloader an object inside the application. This would fix the error handling problem and not require me to hard code paths or create their global variables. But I will have to load many classes (including $ app) before I can instantiate the autoloader.

But am I really in the world of pain because of this problem, I donโ€™t know where to start, are there any tips that I should consider? Can you explain to me which method to use and why?

Thank.

+3
source share
2 answers

As a result of the tips I received on these issues, I searched a little more and found good resources to find out.

What is autoload?

- , . ( PHP). , , , , , , / .

__ autoload() vs spl_autoload_register()

PHP ( PHP.). - __ autoload(), spl_autoload_register(). ? __autoload() , , , spl_autoload_ *. spl_autoload_register() , , , ( , , , ). : spl_autoload_register() __autoload(), .

( PHP): PSR-0 PSR-4

, PSR-4 , , PSR-0, 4 0, (PSR-4) :

, PSR-0.

, ?

, PSR-4 "" PSR-0, . , , , PSR-0 :

\vendor\(sub_namespaces\)class_name

_. :

path/to/project/vendor/sub/namespaces/class/name.php

, YourLibrary

\YourDeveloper\YourLibrary\YourFunction

/path/to/project/YourDeveloper/YourLibrary/YourFunction

, , :

/path/to/project/vendor/vendor_name

PSR-0 , , ( ), :

/path/to/project/vendor/YourDeveloper/src/YourDeveloper/YourLibrary/YourFunction

? , PSR-4,

/path/to/project/vendor/YourDeveloper/YourLibrary/YourFunction

. PSR-4. , , PSR-4 . , PSR-0/4, this .

?

, , , . , , , , , . -, , - . , . - , , ; , SIM-, , , ( ).

+2

, , . . symfony, . , ;)

Classloader http://symfony.com/doc/2.0/components/class_loader.html, . , .

( ) , , .

, , , "" , PSR0 http://www.php-fig.org/psr/psr-0/. , , , .

+2

Source: https://habr.com/ru/post/1629921/


All Articles