Renato Dinhani
Renato Dinhani

Reputation: 36746

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.

Upvotes: 7

Views: 3676

Answers (5)

Oleg Neumyvakin
Oleg Neumyvakin

Reputation: 10322

There is a file /vendor/autoload.php generated by Composer. So after dependencies are installed by Composer it's possible to do the following:

<?php
require __DIR__ . '/vendor/autoload.php';

Upvotes: 0

Sergey Eremin
Sergey Eremin

Reputation: 11076

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.

Upvotes: 2

Homer6
Homer6

Reputation: 15159

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.

Upvotes: 2

Michel Feldheim
Michel Feldheim

Reputation: 18260

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

Upvotes: 2

Sagi Mann
Sagi Mann

Reputation: 3620

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');

Upvotes: 1

Related Questions