Search code examples
phpincludedependencies

What is the right way to load dependencies in PHP?


I have a doubt about the right way/best practice about loading dependent classes in PHP.

I usually put all dependencies in the beginning of each class with a include_once in a way similar to Java imports. Something like:

include_once 'dto/SomeObjectDTO.php;'
include_once 'dao/SomeObjectDAO.php;'
include_once 'util/SomeObjectUtil.php;'

class SomeObjectService{
    #class code here
}

This is the best way to load classes? Or maybe load all classes in a Bootstrap.php? Other ways?

Note that I'm talking about loading my own classes, not complex external classes like frameworks.


Solution

  • Like Homer6 said, autoloading is a php's built in dependency loading mechanism.

    PHP-FIG proposed a family of PHP coding standards called PSR. PSR-0 deals with class naming and autoloading. Here are some links:

    Also, keep in mind, that autoloading comes with a price. There is a lot of string work and work with the fs in the proposed default autoloader(you can implement your own faster autoloader, but it is not going to conform to the standard). This makes autoloading slow when you need to load a lot of classes. So if you needed to load 2 classes only, your approach would be faster and more understandable.