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 all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.