How to use Composer and Packagist in PHP

Composer is the package manager of PHP.

It allows you to easily install packages into your projects.

Install it on your machine (Linux/Mac or Windows) and once you’re done you should have a composer command available on your terminal.

Now inside your project you can run composer require <lib> and it will be installed locally, for example le’ts install the Carbon library that helps us work with dates in PHP

composer require nesbot/carbon

It will do some work:

Once it’s done, you will find some new things in the folder, composer.json that lists the new configuration for the dependencies:

{
    "require": {
        "nesbot/carbon": "^2.58"
    }
}

composer.lock which is used to “lock” the versions of the package in time, so the exact same installation you have can be replicated on another server, and the vendor folder, that contains the library just installed, and its dependencies.

Now in the index.php file with we can add this code at the top:

<?php
require 'vendor/autoload.php';

use Carbon\Carbon;

and then we can use the library!

echo Carbon::now();

See? We didn’t have to manually download a package from the internet, install it somewhere.. it was all fast, quick, and well organized.

The require 'vendor/autoload.php'; line is what enables autoloading. Remember when we talked about require_once() and include_once()? This solves all of that, we don’t need to manually search for the file to include, we just use the use keyword to import the library into our code.

Download my free PHP Handbook!