Composer Basics: What is it and how to use it

Cesar Kohl
2 min readJul 6, 2019

--

Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.

It downloads packages from Packagist and also has its own autoloader to enable autoloading.

Why do we need Composer?

It ensures all developers are on the same page using all the same package versions to run the application the team is coding. Also, it's easy to get up and running very quickly downloading the correct packages. It also enables us to call the autoloading service. And, finally, it makes convenient to upgrade and downgrade all the packages the software is based on. As a matter of fact, it came to be a new standard in PHP software development.

Installing

  • Download and install Composer from https://getcomposer.org
  • I suggest to make Composer available globally in your machine
  • Require your first package following the steps below

Basics

There are two files that control dependencies: composer.json and composer.lock but you will only use composer.json. You can create the file manually or directly call composer to require a dependency.

In this tutorial we'll call the Intervention/Image package. It handles and manipulates any kind of images. Create a project folder and in Terminal type:

$ composer require intervention/image

It will create both files. Now, create a folder /img, download the image below (notredame.jpg) and put the file inside it.

Create a file index.php and put code below in it:

<?php
require "vendor/autoload.php";
use Intervention\Image\ImageManagerStatic as Image;$image = Image::make('img/notredame.jpg')->resize(300,200)->save('img/notredame-2.jpg', 100);echo '<img src="img/notredame-2.jpg" />';

The project folder will be like this:

/composer.json
/composer.lock
/index.php
/img/notredame.jpg

Run the code using PHP. It will create a file /img/notredame-2.jpg. What happened in the file index.php?

  1. It required the Composer autoload. The vendor/autoload.php is requiring Intervention\Image (and all future dependencies you need and call)
  2. It called the dependency Intervention\Image and call it Image
  3. It instantiated Image::make()->resize()->save(), saving /img/notredame-2.jpg
  4. It showed the image on the browser

Conclusion

Composer leverages the management of dependencies calling really quickly what is needed and keeping your code simple and organized. Large projects also use the power of Composer to keep the team concise and avoiding dependencies errors.

If you need the code just clone it via git: https://github.com/cesarkohl/composer-basics

Thank you!

--

--