PHP Composer, Quick guide, First Steps

Just as Node.JS has NPM or Ruby has Bundler, in PHP we have PHP Composer. It is a package manager that makes it easier for us to manage the depedencies of the libraries we work with our PHP Projects.

Installing PHP Composer

If you are a windows user, just download the installer always from their official site: https://getcomposer.org/Composer-Setup.exe

I personally work with Debian Linux, but the steps i am going to show you work similarly in Ubuntu and other Debian child distributions.

We download the PHP Composer

curl -sS https://getcomposer.org/installer -o composer-setup.php

We execute your installation

sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer

Executing the above will throw us the following over the command line.

composer php setup

We will remove the file composer-setup.php

rm composer-setup.php

Finally we are going to execute the command “composer”

composer

The last command will help us to corroborate our setup was satisfactory and will show us the following message in the terminal.

Once this is done we have PHP Composer ready to use.

Basic commands to works with PHP composer

composer init
We execute it at the root of the directory in which our PHP project is located and when we run it, it will ask us for some basic information about or project “Package name, description, dependencies”. The dependencies can be added at any time by editing the file “composer.json” which is generated automatically with this command.
composer install
This command execute the setup of the depedencies added in the composer.json file.
composer require
With this command we will setup the require dependencies and we will add automatically to the composer.json file.
Composer update
With the “composer update” command will download the last depedencie version.

Installing a depedency on an existing project

We will try now to install a dependencie on a project which we have currently active but for this case we will use the dependencie Simple Cache Class

We will get in the project directory and execute

composer init

This command will build our composer.json file and will ask for the following info:

Package name (<vendor>/<name>): danielrosiles/simple_cache_php
Description []:
Author [, n to skip]: Daniel Rosiles <hello at danielrosiles.com>
Minimum Stability []: stable
Package Type (e.g. library, project, metapackage, composer-plugin) []: library
License []: MIT

We will setup the dependecie

composer require voku/simple-cache

By executing the above commands we can already invoke the dependency in our project. And now we only need to invoke in our php code the autoload generated by the PHP composer.

use voku\cache\Cache;
require_once 'composer-path/autoload.php';

Da click aquí para encontrar la versión en español de está entrada.

Share: