# How to use Composer and Packagist in PHP

> Learn how to use Composer, the PHP package manager, to install packages like Carbon with composer require and autoload them via vendor/autoload.php.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2022-09-04 | Topics: [PHP](https://flaviocopes.com/tags/php/) | Canonical: https://flaviocopes.com/php-composer-packagist/

[Composer](https://getcomposer.org) is the package manager of PHP.

It allows you to easily install packages into your projects.

Install it on your machine ([Linux/Mac](https://getcomposer.org/doc/00-intro.md#installation-linux-unix-macos) or [Windows](https://getcomposer.org/doc/00-intro.md#installation-windows)) and once you’re done you should have a `composer` command available on your terminal.

![Terminal showing Composer version 2.3.7 command help with usage options and available flags](https://flaviocopes.com/images/php-composer-packagist/Screen_Shot_2022-06-27_at_16.25.43.jpg)

Now inside your project you can run `composer require <lib>` and it will be installed locally, for example le’ts install [the Carbon library](https://carbon.nesbot.com) that helps us work with dates in PHP

```php
composer require nesbot/carbon
```

It will do some work:

![Terminal output showing composer require nesbot/carbon installation with package dependencies being downloaded](https://flaviocopes.com/images/php-composer-packagist/Screen_Shot_2022-06-27_at_16.27.11.jpg)

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

```php
{
    "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
<?php
require 'vendor/autoload.php';

use Carbon\Carbon;
```

and then we can use the library!

```php
echo Carbon::now();
```

![Browser showing localhost:8888 displaying current date and time output from Carbon library](https://flaviocopes.com/images/php-composer-packagist/Screen_Shot_2022-06-27_at_16.34.47.jpg)

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.
