How does composer know which classes are used?

540 Views Asked by At

I was wondering how Composer knows which classes are used in the scripts that will be executed. Does PHP provide a hooking mechanism with a callback? I'm guessing it's not inspecting the code since the following code works (provided the PHP Redis extension is installed, Redis is running on localhost with the auth token provided and the class_name key is set to the string 'App\Examples\B'):

/app/Examples/A.php
<?php namespace App\Examples;

class A
{
    public function __construct()
    {
        echo "Constructing A!\n";
    }
}
/app/Examples/B.php
<?php namespace App\Examples;

class B
{
    public function __construct()
    {
        echo "Constructing B!\n";
    }
}
/app/main.php
<?php namespace App;

use App\Examples\A;

include __DIR__ . '/../vendor/autoload.php';

$r = new \Redis;
$r->connect('localhost');
$r->auth('GJuqgx[0h-OtO94X7W[9');

// App\Examples\B
$class_name = $r->get('class_name');

$a = new A;
$b = new $class_name;

Running this from the command line produces the expected output:

$ php app/main.php
Constructing A!
Constructing B!

How does composer know to even look for App\Examples\B?

I'd like to emphasize that I am NOT asking how composer knows where to find App\Examples\B, rather, I am asking how it knows that it will need to find App\Examples\B in the first place.

1

There are 1 best solutions below

3
Marcel On

It 's all about the auoloading process. The PHP Introperability Group wrote a recommendation for autoloading called PSR-4. This one is used by composer.

You have to use namespaces in your PHP code. Best practice is to use a unique namespace for your composer packages. Like YourCompany\ModuleName\ and so on. These namespaces are resolved by the composer into a path containing the corresponding PHP classes. The base path is in the composer package configuration (mostly a composer.json file in your package directory). This informations are taken by the composer autoloader to find the right PHP classes.