Complete PHP Composer Tutorial.
Complete PHP Composer Tutorial.
In this tutorial, we want to explain how to use Composer to manage the packages of
software you use in your projects or the libraries that your application depends on.
The idea of a dependency manager is not new in PHP, it already existed in other languages.
programming. Composer has made it possible for us to use this concept as well.
PHP developers to improve our workflow.
Composer summarizes all the tasks of installing libraries, frameworks, and in general
any type of software you use to develop a project. Through a simple
In the declaration, you can mention the libraries you want to have available, and Composer will provide them to you.
will download for you and place them in your project folder. Additionally, when those libraries are
updating the dependency manager will be able to replace your downloads with the latest versions
new, as long as you indicate so.
Finally, it offers you a system that allows you, in a single line of code, to have all the
libraries or programs that you have defined as dependencies, so you don't have to do includes or
requires independents for each element you want to use, they will simply be there.
Composer also works with Packagist, a comprehensive repository of free software with
those packages that you will be able to install automatically via dependency manager.
In this Composer manual, we will be publishing the articles so that you can not only
resolve your doubts about the dependency manager, as well as various common problems
what you could find.
http://desarrolloweb.com/manuales/tutorial-composer.html                                                  Page 2 of 28
                                                                            Composer Tutorial
The following individuals have participated as authors by writing articles for this manual.
The provided text is a URL and does not contain translatable content.                  Page 3 of 28
                                                                                           Composer Tutorial
Composer is a dependency manager for projects, for programming in PHP. That means
to say that it allows us to manage (declare, download, and keep updated) the packages of
software on which our PHP project is based. It has become a tool for
header for any developer in this language who values their time and development
agile.
Are you starting a new project with PHP? Take a look at Composer first because it can help you.
help a lot in the startup and thanks to him you will be able to summarize many of the tasks of
maintenance of the third-party libraries you are using.
https://getcomposer.org
In this article, we summarize the details to understand what Composer is, how it works, and
to install it on your system. First, we will begin by explaining what a manager is
dependencies, then we will see how Composer works to realize what aspects of
Our day to day will simplify us. Finally, we will see how to install it and how to use libraries.
managed with Composer in our PHP code.
discussion.
So, at the start of the project until now we had to go to the page of each one of
the software components we wanted to use, download them, copy them into the folder of
our project, etc. Not only that, when we are in the middle of development, or already in
production, and they change the version of the library, we have to download it again
manually, update the files, etc. No one had died for doing all that kind of
configuration and maintenance tasks, but there is no doubt that they take us time.
All of this without considering that certain software, like a framework like Symfony, depends on
instead of many other libraries that you would have to install manually and also maintain
updated.
To benefit from the workflow that Composer proposes to us, we simply have to
write a configuration file in which we indicate which packages we will require. The
the file is a simple JSON in which we indicate things like the author of the project, the
dependencies, etc.
Below you have an example of JSON where we declare several parameters of our
application.
desarrolloweb/testing-composer
"require": {
5.2.*
Then we will break down this code so that each of its parts is understood, like this
as we will see what other information we can put in this JSON. The idea is to see how simple it is
What it means to declare which libraries or software you are using and thus leave our project ready.
for the 'magic' of Composer.
Once we have defined the dependencies in our project, we must install them. This is done
we accomplished it with a simple command in the terminal where we asked Composer to
install:
composer install
                           Note: That command may vary depending on the installation you have on your system.
                           Composer. We will specify in a future article various situations in which we have
                           Let's generate variants of the same command. For now, we will stick to one.
                           presentation of Composer, but then we start learning in detail here in
                           WebDevelopment.com
Once that command is launched, Composer will take care of going to the software package repositories and
download those mentioned libraries, copying them into your project folder.
Once the process is finished in your command console, you will find in the folder of your
I propose a directory called 'vendor' where the declared libraries will be. We only need to
it is necessary to do the includes so that they are available in your applications and for that we also
help Composer.
We will simply have to make a single include or require in our code and all the
libraries will be available to use.
require 'vendor/autoload.php';
Packagist
To finish persuading you and to tell you the complete introduction, you need to take a look at
Packagist. It is the repository of packages that can be installed via Composer.
On the Packagist page, you will find a search engine that can give you an idea of the amount of
material that you find available to use in any PHP project.
Just search for any concept that interests you, like email, template, wysiwyg,
etc. You will see that several options appear classified by popularity, downloads, etc. In addition
About each package you find information and the necessary code to declare your dependency.
in the Composer JSON.
Conclusion
I hope that what we have seen so far has caught your attention about this tool.
The truth is that it is very useful and as we say, once you start using it, you realize everything.
the work that removes you from the environment, not only in the unloading of the packages, but also in the
updates of the libraries with the command 'composer update' that we will see later.
We know that we have left many things unsaid, such as the installation process and the
detail of the JSON, but we will see it in upcoming articles. For now we wanted
to introduce you to the dependency manager and to let you know why PHP developers use it
we have adopted with such enthusiasm.
In addition to the upcoming articles where we will explain the details of the workflow.
With Composer for dependency management, we are now going to present a video of our
YouTube channel where you can find summaries of some of the basic steps of use
Composer.
In the previous article, we got to know Composer, the PHP dependency manager that allows us to
it allows to improve the PHP development workflow when we are using third-party libraries,
not only at the moment of creating a project but also during its maintenance.
On this occasion, we are going to focus on explaining the installation process. As you will see,
it's such a simple process that can be summarized in a terminal command, but we want
comment on some installation variants and issues we might encounter,
with their solutions.
Install Composer
To have this marvel in our system, in order to manage our dependencies
In PHP, you must install it first. The process is quite simple. If everything goes well, it boils down to these
actions that depend on your operating system.
Windows:
If you are on Windows, you will use a traditional installer. No secret. It's a wizard and you go.
going through several windows, next, next.
Linux / Mac:
If you are on Linux or Mac, you will use the command line to install Composer. It's that simple.
how to execute this instruction:
http://desarrolloweb.com/manuales/tutorial-composer.html                                               Page 8 of 28
                                                                                                               Composer Tutorial
                             Note: That command requires Curl, if it fails you can try doing the same but with the
                             PHP command.
As a last resort, you can also manually download composer.phar and place it in the folder of
Your project where you want it to be available.http://getcomposer.org/composer.phar
This will download the composer.phar file to your folder, which is a PHP executable. The .phar
you can run them from the command line like other terminal commands. That file is
Just the one you invoke to load the dependencies or update them, we will see that shortly.
In the case of having made a particular installation for a project, you will place the
composer.phar in the root directory of your project, so that you can later invoke it to
install the dependencies. However, if you want, you can also install it in a way
global in Linux if you place the composer.phar in another path.
mv composer.phar /usr/local/bin/composer
Note: If that command doesn't work for you, just try doing it as a superuser.
And if you are on Mac OSX, the easiest way to have Composer globally is to install it.
via 'homebrew', the package manager for Mac systems. It's a somewhat longer process, but
you will also benefit from having homebrew on your machine to install other software that
you may need. The Composer documentation itself provides us with the commands that
we should execute.
                           Note: First you will have to install Homebrew itself, as explained on the page.
                           http://brew.sh/
brew update
But watch out! In my specific case, that series of commands returned a problem saying that
The Composer dependency was not there with php53, php54, php55, or php56. That despite having
Installed PHP with Mamp. I solved it by executing the command:
That installed php56 with brew and then everything worked well when I ran the command.
The openssl extension is missing, which means that secure HTTPS transfers are impossible. If
Possible you should enable it or recompile PHP with --with-openssl.
Don't worry because you don't have to recompile anything! Just open the php.ini file and
search the line:
;extension=php_openssl.dll
Unable to access external content. Please provide the text you would like translated.                                  Page 10 of 28
                                                                                      Composer Tutorial
Remove the semicolon ';' in front, because it makes that line count.
As a comment. Then the openssl extension will be active and you will be able to install it.
composer normally.
Another problem you might encounter in Windows, although no longer during installation but in the
the use of Composer, is that the JSON file is malformed. If you check the syntax of your JSON and
you find that everything is fine perhaps your problem is the encoding or character set. The
JSON files must be written in "UTF-8" encoding, and you must not use BOM.
You can change the encoding with your preferred editor, each editor has the option to save.
with a specific encoding in a different part.
Conclusion
For now, I think that's all you need to know so that installing Composer doesn't become difficult for you.
no problem. In the following article, we will focus on explaining in detail the use of
Composer.
Using Composer
In this article, we provide you with all the keys to using Composer, the manager of
PHP dependencies. Declare dependencies, install them in a project or
to update them.
In theComposer Manualwe have already been able to address several issues related to Composer,
the popular dependency manager that all PHP developers should use to
improve our workflow.
This step is very simple, as it basically consists of creating a text file with the
configuration that we need for the project. We can do it in two ways:
The provided text is a URL and does not contain translatable content.                       Page 12 of 28
                                                                                               Composer Tutorial
But keep in mind that whether you create the composer.json interactively or in a way
manual, once created you will have to start the process of installing dependencies, with
"composer init", as we describe later in this same article.
The assistant for creating this file is then launched from the root of your project.
with the command:
composer init
Once this command is launched, the terminal will start to gather data from our project, such as the
name
The provided text is a URL, and I cannot access or translate content from external websites.             Page 13 of 28
                                                                                           Composer Tutorial
The process repeats for each package you want to install. Then it all starts again.
for the dependencies you have in development (require-dev), which are all the libraries that
you need in your project when creating your code base, but do not need to be in the
production server, such as testing libraries or data generation tools
fake to initially populate databases.
Once the wizard is finished, it will present us with the code of the composer.json that is going to be generated.
And if we tell him that it is correct, the composer.json file will be created with the configuration.
selected.
Since composer.json is a plain text file, if we find it necessary we can create it.
manually like any other file in your project. You should place that file in the
the root folder of your project and its name must be composer.json.
The JSON file is used to indicate some data about our project, as well as the
dependencies it has with other packages that you find on Packagist.
webdevelopment/testing-composer
"require": {
5.2.*
0.9.*@dev
composer." Two names are always used, one the company or creators' nick and the other the
name of the project itself. Then with the require field we are indicating that we are going to use
two libraries, on one hand the phpmailer from phpmailer and the kint from ravener.
Additionally, you will notice that each package has a required version. For example, in phpmailer.
we declare version "5.2.". This means that you will always install version 5.2.x (the
most recent of 5.2). But you could have declared "5." There are several operators for
specify the version. The best thing is to check the Composer documentation to learn about them
all.
                          Note:In the following article of this manual, we will explain in more detail thesyntax
                          and the data you can specify in the composer.json.
You have to run that console command from your project folder. Open the terminal.
and you are located in the folder where you have created the composer.json.
Depending on the installation we have made of Composer, the command may have
slight variations. This may also depend on your operating system.
composer install
                          Note: Logically, that command won't work for you if you haven't installed it previously.
                          Composer.
If you are on Linux/Mac and have followed the steps to install Composer properly
The provided text appears to be a URL and does not contain translatable content.                                            Page 15 of 28
                                                                                                              Composer Tutorial
composer install
This is the case for Mac OSX after installing Composer through Homebrew. But
In the case of Linux you may have to do:
composer.phar install
                           Note: To find out how to install Composer and about the global and local variants on systems
                           Linux / Mac OSX, please check the article aboutInstall ComposerIf you have any
                           it's not a bad idea to check the Internet as many developers surely
                           they have been through it before.
                           At this point, I want to mention a page that has clarified my doubts, on askubuntu.
                           http://askubuntu.com/questions/116960/global-installation-of-composer-manualwhere
                           Additionally, a user proposes a way to create an alias so that in Linux you don't have to
                           run 'composer.phar install', otherwise just 'composer install'.
alias composer='/usr/local/bin/composer.phar'
                           Logically, you must have already made your Composer installation global as you have.
                           explained in the article about the installation mentioned in this note.
composer update
The provided text is a URL and does not contain translatable text.                                                        Page 16 of 28
                                                                                                                         Composer Tutorial
                           Note: The variations of that command will be more or less the same as those of the command.
                           "composer install" depending on our composer installation. Maybe on your system
                           you have to do something like 'php composer.phar update'.
                           With that, Composer will automatically download the libraries that have been updated, or
                           those that have been added to the composer.json and will be placed inside the 'vendor' folder
                           of your project.
When you install a dependency via Composer, it creates a directory called 'vendor' which is
where all the libraries you requested are installed. Also, in that same folder
you will find a file called 'autoload.php' which is the only script you need to include from
PHP.
<?php
require "vendor/autoload.php";
Now you can access the classes created by the libraries declared as dependencies...
It's as simple as this. You don't have to do anything else. Whenever you need a class or
a function declared in the dependencies of your composer.json will be available for
you without having to take other actions. As you will see, this mechanism also allows you
it allows you to avoid creating a series of includes or requires in all your PHP files, reducing your
code.
Using Composer will undoubtedly make your life much easier as a PHP developer on a daily basis.
Once you get used to this workflow, very simple as you have seen, no
you will understand how you could have lived so long without him.
The provided text is a URL and cannot be translated as it does not contain text.                                                   Page 17 of 28
                                                                                  Composer Tutorial
In theComposer Manualwe have already explained the entire workflow that will allow you to
adopt Composer in your day-to-day PHP development. Really with what you know and a
quick reference in the documentation to consult details that we may have missed
escape, you have everything you need to use Composer.
However, we have skimmed very lightly over the structure of the composer.json file.
that serves us to declare the characteristics of our project and the dependencies that
may have.
But watch out, the composer.json is not only useful for Composer to know the dependencies.
what you need to install for your project, it also applies in case you want to release your project
as a package for others to use and publish it on Packagist. In this article
We are going to focus more on what you need to define your dependencies.
The provided text is a URL and does not contain translatable content.                       Page 18 of 28
                                                                                  Composer Tutorial
for a project. These are the data that you would need to send to Packagist, but that are not
necessary at an internal level for Composer to function, but rather to label your
development, mention authors, etc.
name
It is used to indicate the name of the author, consisting of two parts, the "vendor" (the company or
nickname of the developer or group that created it) and the name of the project itself.
Of course, a vendor can create various libraries or packages, and they would all remain
linked to the same vendor with different project names.
description
It is the description we offer for this package. It is usually a single line of text.
homepage
authors
It is an array with the authors of the project. Each of the elements of that array is in turn a
JSON object where various data can be indicated: name, email, homepage, role.
of the project).
"authors": [
algo@desarrolloweb.com
http://www.desarrolloweb.com
Project Manager
},
Alvaro Martínez
algo@escuela.it
http://www.school.it
Beta tester
require:
It is an object with a series of key/value pairs that define each of the dependencies that
Composer must be installed for our project. In the key, we must indicate the name of the
package that depends (what you get from the Packagist site) and as a value we indicate the version
that we wish to be installed, or the range of versions.
"require": {
0.6.*
>=4.0
dev-master
In the key/value pairs of each of the dependencies, the vendor name part and the
The library is very easy to obtain. You simply go to Packagist, search for, and choose the package.
whichever suits you best and copy the name string. For example, 'respect/validation' indicates
"respect" is the vendor and "validation" is the name of the library.
The part of the version can also help you with Packagist, as you will find the list of
released versions of that library and available as packages. What you will see is that the
expression that defines the version has some 'wildcard' characters that you must learn to
to deal with. In general, you can use these expression variants.
                  Exact version: you indicate to Composer that it must install an exact version, and only that.
                  It means that it will never update the package for you, because your project must have that.
                  version and not another. For example, "4.3.1".
                  Version range: allows indicating versions that are greater than one
                  determined, lesser or that is between one version and another. For example ">=2.0".
                  Wildcard: Allows stating any version of a major release. Well, you can use
                  something like '4.' to indicate that version 4 should always be left and anything else. Or something.
                  more restrictive like '4.2.' which will always set you to version 4.2.x. Logically, in
                  In this case, when you update, the most advanced version allowed by that will be set.
                  wildcard.
                  Tilde (the tail of the eñe): it allows indicating the version in a different way,
                  next significant version. For example, "~2.2" will always leave you the major version
                  or equal to 2.2 and less than 3.0. For example, "~2.2.1" will give you the next higher version
                  equal to 2.2.1 and less than 2.3.
                  It also allows you things like "dev-master" which will be the current version of
                  development, which may be unstable. "1.0.*@beta" that will allow you
                  put beta versions or "@dev" that also refer to development versions that
                  they can suffer instability.
For now, that's all. With the information you have, we are sure that you will be able to get it.
use all of Composer to manage the dependencies of your PHP projects.
How to include the code of the packages installed via composer in pages
PHP through class autoloading.
One of the fundamental advantages of using Composer is that we can stop worrying about
how to install, update and include dependencies in PHP code. About this
the last point is the one we are going to focus on in this chapter.Composer Manual.
autoload.php file
The autoload.php file is created automatically by Composer in the 'vendor' folder and contains
the code to load your libraries automatically, on demand as needed
keep using it.
Let's have one or several dependencies, the only file we need to include in a
The PHP page of the project is the aforementioned autoload.php.
//autoload of composer
require 'vendor/autoload.php';
                            Note: don't worry about having many dependencies and only using a few in one.
                            specific page. This autoload file does not load anything special, it just has the script
                            from class autoloading, it will not become heavier for PHP than strictly necessary,
                            Well, only the classes you are using in your code will be loaded.
Unable to translate URL content directly. Please provide the text you want translated.                                      Page 22 of 28
                                                                                                          Composer Tutorial
The 'vendor' folder should be at the root of your project, typically outside the directory.
"document root", so that it is not directly accessible through a URL of your website.
But of course, it depends on where you load this autoload file from, the path of your include can
be different.
For example, this makes use of a static method from a templating system called Plates,
to initialize. Note the namespace "League\Plates". The class name is "Engine".
That same code could also be done with the corresponding 'use' in which we indicate the
class and its namespace. Once it is declared that this class will be used in the corresponding
namespace, we can now invoke its methods or the constructor without indicating the namespace
complete.
use League\Plates\Engine;
It seems obvious, but we want to emphasize that this code would not work if the
corresponding autoload with PHP, which is provided by the file vendor/autoload.php.
                            Note: If you need it, you can find more information about namespaces in the
                            articleNamespaces in PHP.
This field allows us to specify a namespace and the classes that are behind it.
namespace.
"autoload": {
This indicates that the classes of the namespace 'MiNamespace' need to be retrieved from the directory
my_folder" (assuming that "my_folder" is hanging in the root, so it would be a
brother of the "vendor" directory.
Just one single detail. Once you have set up Composer's autoload system, you must
run the command "dump-autoload" to regenerate and optimize the entire process
of Composer's class autoloading.
composer dump-autoload
Now that we have the regenerated 'vendor/autoload.php' file, we will be able to have
Classes of this namespace available for autoloading.
About the self-loading system, it is also good to know that it can be configured in real time.
of execution, and not only through the composer.json. This is useful when there are certain
classes that are only used at a certain time, like testing classes, and we don't need them
not at all when the site is functioning generally.
You get it thanks to an instance of a 'loader' object that returns the require of your
autoload.
$loader->addPsr4('MyNamespace\', 'my_folder');
Conclusion
There isn't much more to say about Composer's class autoload system. It really is
just start using it and enjoy its comfort.
You can find more information in the composer documentation, on the page of
autoloading in theComposer Manual.
The provided text is a URL and does not contain content to translate.                                                 Page 25 of 28
                                                                                    Composer Tutorial
This article is simply a list of situations that can lead to problems in usage.
of Composer in day to day. Logically, this list is just a compilation of the things that I
they have happened personally, so your problem might not be here. (If you find
news that can help other people can be posted as comments)
composer self-update
Remember that you may have to run that command as a superuser (sudo composer
self-update). Also remember that if your composer installation is not global possibly
you have to invoke it by directly calling composer.phar through the PHP interpreter
(php composer.phar self-update). In theinstallation articledo you have more information about it
what is installing globally
Malformed JSON
                                                                                               Page 26 of 28
                                                                                   Composer Tutorial
This error is very easy to detect. If you have malformed your JSON, you will have an error like:
In the article of theComposer installationwe explain that one of the typical problems, in
Windows is not using UTF-8 encoding. It is necessary for composer to consider.
that the JSON is well-formed.
If you are using UTF-8, it must be a syntax error, some missing quotes, a comma, or something.
Like this. If you go crazy trying to find the error, try using a JSON Validator:
The provided text does not contain any translatable content.
Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 72 bytes) in
phar:///usr/local/Cellar/composer/1.0.0-
alpha8/libexec/composer.phar/src/Composer/DependencyResolver/RuleSetGenerator.php
on line 123
This can be solved by allocating more memory for the PHP process, as indicated in the php.ini, in
the configuration variable memory_limit.
2048M
The value of memory_limit accepts integer numbers, in which case you are specifying a
amount of Bytes. But it also allows you to end with a unit ("K", "M", "G") indicating
the value in Kb, Mega or Giga.
To find the php.ini for the command line (PHP CLI), you just need to do this
command.
php -i
That will show you a huge amount of data, similar to what you get with phpinfo().
You have to search through all that output for the text 'php.ini' to find the path of the file
configuration being used.
When you invoke the composer command by default, a time is assigned to it.
processing that is 300 seconds. This time may be insufficient in case the
packages to download are heavy or in slow Internet connections. If this happens to you, you will receive
an error that among other things will have this text.
The process 'git clone [...] exceeded the timeout of 300 seconds
In this case, you can invoke the command by assigning a new maximum value in seconds for
perform the update or installation operations of the dependencies. It would be something like: