Composer -the PHP dependency manager
¿What is composer?
Let’s allow composer creators to define their program, I Thought is the best way to understand it in a few lines what it is.
Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.https://getcomposer.org/
¿What is a dependency?
Is an application or library created by us or third parties(other creators) that we can add to our project with composer.
Let’s see an example of this, if we want to send emails in our app we probably use PHPMailer and dbal for that we can manage this with composer. With this, we are not coping and pasting part of libraries to make it work. When you are using composer, all these dependencies go to a folder called vendor that will have all the necessary to run these dependencies or modules.
To install composer on Windows, it’s simple, you need to download the installation archive from composer page https://getcomposer.org/download/ and execute it. The installer will download composer and defines a route for the environment that will allow us to use composer command globally.
To install it on Linux, you need to use your terminal. Depending on what type of installation locally or globally are the steps you need to follow.
Locally: to install it locally, you need to run the commands in the composer page in the folder of our project.
This will download a file called composer.phar in our directory or folder, then he can run composer with
I especially recommend installing composer globally, you can use it in your PHP projects without installing anytime you need it, and it is easier to write composer commands when it’s globally installed.
Globally, when you are installing composer globally you can run this commands page everywhere and then the generated file composer.phar
mv composer.phar /usr/local/bin/composer
You can know what commands you can use running this command
How to use Composer?
Create a file with the name composer.json in our project, this file describes the dependencies of the project and other information(metadata) for example license, author, version description, etc.
This is an example of a Laravel project composer.json
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"php -r \"file_exists('.env') || copy('.env.example', '.env');\""
"php artisan key:generate"
"php artisan optimize"
"php artisan optimize"
With require and require-dev we are specifying what packages the project require then you can run:
php composer.phar install
After this, our project will install all packages that are needed.
Searching packages for our project
At this moment probably you are thinking about how I obtain packages for my project and don’t reinvent the wheel, With this in mind exist Packagist https://packagist.org/