Skip to content

How to use Composer and Packagist in PHP

New Course Coming Soon:

Get Really Good at Git

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.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my PHP Handbook

Here is how can I help you: