Shoe
Shoe

Reputation: 76240

Autoloader converting namespace into folder path

Is it good to use an autoloader that load root/app/model/test.php when trying to use App\Model\Test? In this way every class should be organized accordingly to its namespace.

Is this a good approach? If not, why? what would you suggest?

Should I define a specific array namespace => path that will assure that we are not loading an unexpected file? this way I would have to set every time something like $map['App\Model\Test'] = 'root/app/model/test'; and this would basically delete all the fun of autoloader. Isn't it?

Upvotes: 0

Views: 995

Answers (1)

Grigorash Vasilij
Grigorash Vasilij

Reputation: 713

  1. It is a rather "standard" approach used in OOP
  2. Usually autoloaders are faster when they have a classmap ($map) injected into them. This is because they don't have to run through the include paths to look up the file with the class being instantiated. Give them an absolute file name, and you'll decouple them from the include path. Providing a $map also allows you to organize your classes in another fashion (not just filesystem-based naming). Apart from this, there are also class map generators that you could run before to actually achieve this and not have to (re)do it by hand each time you rename or move some class. During development, however, it is more convenient to use the standard autoloading logic (no classmaps), because keeping in sync files and the classes declared in them can get quite tedious and have little do with development itself.

Reducing the number of boilerplate code is not the only purpose of the autoloader:

  • you load only those class declarations that are actually needed in your code; not all or some declarations; only those that are used
  • it ensures your include_once and require_once in respect to classes happen only in autoloading
  • your classes don't focus on loading files; they focus on their function

Upvotes: 1

Related Questions