6

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.

Renato Dinhani
  • 35,057
  • 55
  • 139
  • 199

4 Answers4

2

PHP's you can register your autoload method. Symfony 2 contains a nice class to do it with.

http://php.net/manual/en/function.spl-autoload-register.php

I've adapted it to work with the library that we've written.

https://github.com/homer6/altumo/blob/master/source/php/loader.php

https://github.com/homer6/altumo/blob/master/source/php/Utils/UniversalClassLoader.php

This adaption allows you to have namespaces that do not require the top level namespace to have the same folder name.

Homer6
  • 15,034
  • 11
  • 61
  • 81
2

Since version 5.3 PHP supports namespaces. This allows you to have a package and class hierarchy just like you know them from C++ or Java.

Check out those resources to learn more:

http://www.php.net/manual/en/language.namespaces.basics.php

http://php.net/manual/en/language.namespaces.importing.php

Michel Feldheim
  • 17,625
  • 5
  • 60
  • 77
2

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.

Sergey Eremin
  • 10,994
  • 2
  • 38
  • 44
1
set_include_path(get_include_path()
        . PATH_SEPARATOR . 'path1'
        . PATH_SEPARATOR . 'path2'
);

// auto load classes:
function autoloadClasses($className) {
require_once $className . '.php';
}

spl_autoload_register('autoloadClasses');
Sagi Mann
  • 2,967
  • 6
  • 39
  • 72