Need help understanding the use of Composer for PHP libraries

hi there everyone!

In the past, I’ve always downloaded a library from Github, added it to my includes directory then required the necessary files in my scripts but it seems that today, Composer is the only way you should handle using these libraries and scripts.

When installing something via Composer for use in a PHP script, does this mean it will load this library for any executed PHP script or do you still have to require a file(the instructions don’t mention requiring a file after composer install)? If it’s loading for all PHP scripts, isn’t that less efficient? Is it for all users on that server or just the web directory that it was installed in?

Any help understanding the benefits and cautions of using Composer to add these scripts would be greatly appreciated.

Thanks for your time!

It’s not loading the entire library, it’s loading an autoloader.

An autoloader is a function that is called by PHP when it encounters a class it hasn’t loaded yet.

So as a small example:

<?php
use PHPMailer\PHPMailer\PHPMailer;

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

$mailer = new PHPMailer();

As soon as you call new PHPMailer() PHP finds it doesn’t know what that class is because the file it lives in has not been required before. So it calls the autoloader, provided by composer, and it will return PHP a path with the file to require in order to get that class. After that is done the script continues.

Composer is mostly because you don’t have to have all dependencies in your project, which saves space and avoids large Pull Requests for updates. Also, upgrading packages is as simple as composer upgrade and it will upgrade all your packages in one go.

3 Likes

Thank you very much for your help.

As an example, I would like to use Guzzle. The docs state to install via composer:

composer require guzzlehttp/guzzle:^7.0

then in my PHP script to load via:

require 'vendor/autoload.php';

Does it matter what directory I’m in on the target machine when running the first line? It seems so because the second line seems to be pointing to a relative path.

You need to require the path where autoload.php lives.

So yes, that particular line may need to be altered for your situation.