Share via:

PHP: Installing and Using Composer

How to install and use composer locally, without the need to write sudo all the time.

82 views

Edited: 2019-10-16 17:47

PHP Article

Before we can use composer to install things we need in PHP projects, we will need to download and run the setup file. To do this, it is recommended to follow the official instructions on this page:

https://getcomposer.org/download/

The setup file composer-setup.php makes sure your php.ini is configured correctly, and alerts you if not.

It also downloads a file, composer.phar, which should be moved to ~/.local/bin.

While moving the .phar file, we also rename it to composer, since the extension is not needed.

mv composer.phar ~/.local/bin/composer

Placing composer in this location allows us to use composer without having to use sudo, which is very convenient.

Note. The ~/.local/bin/ location can also be used for your own custom scripts and binaries.

Installing things with composer

Now, to install something, we can navigate to the project directory. If you are using a typical Apache virtual host (vhost) setup, this will probably be something like:

cd /var/www/MyProjectName/

Within the project root, we can now try to install PHPMailer (without sudo):

composer require phpmailer/phpmailer

This will create the vendor directory in the root of your project. The vendor directory will contain all the dependencies, such as PHPMailer, that we choose to install using composer.

Using the autoloader, we can then use the dependency we just installed like this:

// index.php
// Composition Root
//
define('BASE_PATH', rtrim(preg_replace('#[/\\\\]{1}#', '/', realpath(dirname(__FILE__))), '/') . '/');

require BASE_PATH . 'vendor/autoload.php';

// PHPMailer Object
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->addAddress("someone@example.com", "FirstName LastName");
// ...

Comments