سؤال

Lets say I'm running a PHP app like Magento, PrestaShop.

Now these system have their own complex autoloaders to load controllers based on routes, required classes, models, etc.

Most of the time as a developer I create module to implement some sort of custom functionality. These modules reside in /modules/mymodule/. Some of these modules have their own classes like models, tools, etc.

I want to know if it's good practice to use autoload.php in modules (they opposite being including files manually)? What if there are 20+ modules and all of them have registered an autoloader? Any performance/architecture issues?

The autloader function is a simple one:

spl_autoload_register(function ($class) {
    include('classes/'.$class.'.php');
});

Namespaces are not allowed as of yet (PHP 5.2 support). Class names are usually namespaced.

هل كانت مفيدة؟

المحلول

Okay, first things first: you're running PHP 5.2!? There's not really much reason to stay with that other than having out of date servers, and that means it's either time to switch hosts or update your servers because PHP 5.2 has some major known security holes which aren't ever going to be fixed. This'll also give you access to a bunch of new features, the most relevant to your situation being namespaces, which will actually come up later.

The current best/most common practice for autoloading is PSR-0/PSR-4 which establish clear, consistent conventions for autoloading. This is mostly thanks to the fact that Composer has become such a widely-used part of the PHP toolchain. The main advantage of using consistent autoloading where classnames/namespaces are tied to the file system is that you don't need to have multiple autoloaders registered, you only need one which can do most of the lookup work for you.

So in the case of something using PSR-4, then a class like Namespace\Namespace2\Classname (or Namespace__Namespace2__Classname in the pre-namespace world) maps to a with a path like Namespace/Namespace2/Classname.php, which the autoloader can easily programmatically include for you once. From a performance perspective, it's faster than using require_once*, and from a coding perspective, it means you don't have to remember to add your include/require statements in every file. What's more, you don't have to keep those include statements up to date when you want to rename or move a class--the autoloader takes care of linking everything up for you.

*I should concede that opcode caching makes the speed argument largely irrelevant for the most part

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى softwareengineering.stackexchange
scroll top