Let’s dig deeper in composer internals.
Where can I find packages for composer?
Many of packages which we can use as project dependencies can be found on packagist.
Let’s say our project depends on Twig library.
require section in
composer.json file will look like this:
1 2 3
The file says we want Twig version at least 1.12.0. Composer will install the newest minor version (e.g. 1.12.1 or 1.12.3) of major version 1.12. We’ll never get Twig 1.11 or Twig 1.13 or Twig 2.0.
We can define an exact version of Twig like this:
Maybe we want any newest development version. It’s simple:
Now composer will install newest bleeding-edge version from
from Twig’s Git repository. The used schema
Using custom dependencies
If you have your own libraries you want to use in a project, add
composer.json. It contains array of
Let’s say you want to use a library hosted on github. Then the
section can look like this:
1 2 3 4 5 6
type field we said it’s a Git repository and an address of the repository
is defined in
Then, you can edit the
1 2 3 4
composer update will fetch code of “example” library from
How my project knows about installed dependencies?
autoload.php file in
vendor directory. The file takes care
of dynamic autoloading of all dependencies. Dynamic means all required files are loaded
when they are needed. If we had defined 20 dependencies, it would be very inefficient
and slow to load all files.
When some dependency class is used for the first time, composer’s Autoloader gets called and tries to find and load needed files.
I believe an example below enlightens the question. All you need to do is to include
autoload.php file in your project.
1 2 3 4 5 6 7 8 9 10 11 12
The example is very simple, I just wanted to show dependency autoloading just works. By the way, the output is:
Number of loaded files: 6 Number of loaded files: 9
First time a counter was called there were loaded only composer files. Next time composer loaded more files required by Twig.
Very interesting topic about autoloading of your own code is explained on composer official guide.
This article was also published on my school blog.