0% found this document useful (0 votes)
7 views28 pages

Complete PHP Composer Tutorial.

This document presents Composer, a dependency manager for PHP that allows you to declare and manage the libraries used in a project easily. It explains that Composer automatically downloads and keeps the declared libraries updated through a composer.json file. It also introduces Packagist, a repository where compatible packages with Composer can be found.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views28 pages

Complete PHP Composer Tutorial.

This document presents Composer, a dependency manager for PHP that allows you to declare and manage the libraries used in a project easily. It explains that Composer automatically downloads and keeps the declared libraries updated through a composer.json file. It also introduces Packagist, a repository where compatible packages with Composer can be found.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Composer Tutorial

The provided text is a URL and cannot be translated. Page 1 of 28


Composer Tutorial

Introduction: 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.

You can find this manual online at:


Invalid input. Please provide text for translation.

http://desarrolloweb.com/manuales/tutorial-composer.html Page 2 of 28
Composer Tutorial

Authors of the manual

The following individuals have participated as authors by writing articles for this manual.

Michael Angel Alvarez

Miguel is the founder of DesarrolloWeb.com and the platform of


online training EscuelaIT. It started in the world of web development
in 1997, turning his hobby into his job.

The provided text is a URL and does not contain translatable content. Page 3 of 28
Composer Tutorial

Composer, dependency manager for


PHP

Composer is an essential tool for developers in PHP.


that allows for agile management of a project's dependencies.

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.

Why a dependency manager


When you start a project in PHP, which is already of a certain complexity, the library alone is not enough.
of native PHP functions. Generally, we all use some third-party library or another.
developers, which allows us to avoid starting everything from scratch. Whether it's a framework or something else.
more limited as a system for debugging or sending emails, form validation, etc.
Anything you might need has already been created by other developers. If you are not...
using no library you might be wasting your precious time, but that is another

The provided text is a URL and cannot be translated directly. Page 4 of 28


Composer Tutorial

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.

Package managers help us summarize the tasks of downloading and maintenance of


the project versions to always be up to date. They already existed in other languages
programming and they were particularly useful to us like npm in NodeJS. Now the
PHP developers also have this tool thanks to Composer.

How Composer works


Composer allows us to declare the libraries we want to use in a project. Its use is
extremely simple, what encourages anyone to use it, regardless of their level
technician.

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.

The JSON file must have a specific name: composer.json

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

Unable to translate content from the provided URL. Page 5 of 28


Composer Tutorial

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.

The URL provided does not contain any translatable text.

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.

Unable to access the provided URL or retrieve its content. Page 6 of 28


Composer Tutorial

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 the next article, we will detail the installation process of Composer.

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.

To view this video, it is necessary to visit the original article at:


http://desarrolloweb.com/articles/composer-dependency-manager-for-php.html

This article is the work of Miguel Angel Alvarez.


It was first published on 10/17/2014
Available online athttp://desarrolloweb.com/articles/composer-dependency-manager-
para-php.html

Unable to access the content of the URL provided. Page 7 of 28


Composer Tutorial

How to install Composer

Installation of the Composer dependency manager on your operating system


so that you can start using it in your projects.

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:

curl -sS https://getcomposer.org/installer | php

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.

php -r "readfile('https://getcomposer.org/installer');" | php

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.

Global or specific installation to a project


Here is an important clarification that may interest you because depending on
Hello, there are slight differences in the use of Composer. It is about having a global installation of
Compose or simply have it available in a specific project.

When you install it on Windows, Composer will be available anywhere on your


system. It is a global installation, which means that wherever you are in the directory, you will be able to
invoke the Composer command. I think it's the most convenient, so if you are a user of
Windows you don't need to read more about this point.

However, with the instructions we have provided to install it on Linux/Mac, only it


you will have available in the folder where you were when you launched the Curl command. It
you would have to install it once for each project, which is not an unreasonable thing, but
what can be improved.

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.

sudo mv composer.phar /usr/local/bin/composer

And if you are on Mac OSX, the easiest way to have Composer globally is to install it.

Unable to access the content of the provided URL. Page 9 of 28


Composer Tutorial

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

brew tap homebrew/dupes

brew tap homebrew/php

brew install composer

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:

brew install php56

That installed php56 with brew and then everything worked well when I ran the command.

brew install composer

Note: I have to acknowledge that I am unaware if simply in the 'brew tap


"homebrew/php", indicating the version of PHP we want, can be resolved.

Possible problems in Windows and their solutions


The process of installing Composer on Windows is very simple. However, during the
Installation can give you a common problem that honestly scares you a little when you see it,
but it is very easy to solve. At least I have encountered that problem in
Windows in my PHP installation under Xamp.

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.

This article is by Miguel Angel Alvarez


It was first published on 23/10/2014
Available online atUnable to access external links.

Unable to access external URLs. Page 11 of 28


Composer Tutorial

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.

By now, we should have it installed and some important concepts clarified


when we want to work with Composer. Now we will see how to declare a series of
dependencies and how to install them in our project through the command line with
Composer. We will also see how to update our dependencies once it has been started.
the project.

Create the composer.json file


Article use Composer updated in 2018: To start using Composer in a
project we must take a first step, which consists of creating a file called
"composer.json", whose utility is based on managing all the dependencies of a project with
Composer. We already explained it in the first article of this manual about Composer, but it
we mention again: it is a text file in JavaScript object notation
(JSON).

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:

Interactively, through a command line assistant


Manually, by creating the file in the root of our project and placing the
code by ourselves

Obviously, it's easier to do it interactively, so let's start there.

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.

Create the composer.json file with "composer init"

Oncecomposer installedwe have the 'composer' command at our disposal in


terminal. This command has a series of possible operations, including which
find 'init', which is used to initialize a project, creating the corresponding one
composer.json automatically. Apart from giving us less work, it is an option.
interesting because it saves us mistakes and work time when writing the composer.json.

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

Later it will ask us if we want to install the dependencies interactively. If


We know which packages we want to install from the start, we can say yes. If we don't know.
What we want to install, then we will have to tell him no. The interactive system you
it will allow you to search for words in any dependency and will offer you several possibilities to
installation, from which you can choose the one that interests you.

For example, if we want to install a package calledplates (to create templates in


We can search for it and select it from the list it offers us. Then it also gives us...
it will ask for the version of the library we want to install. If we want the latest version
we simply leave it blank, as you can see in the following image:

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.

Manually create our composer.json file

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.

As a sample, let's take a look at the contents of a sample file.


composer.json.

webdevelopment/testing-composer

"require": {

5.2.*

0.9.*@dev

In this file, we are indicating that our project is called "webdevelopment/testing-


Unable to access or translate content from external URLs. Page 14 of 28
Composer Tutorial

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.

Installing the libraries or software defined as dependencies


Once that json is declared in the folder of our project, you have to run a command
for composer to start, review the packages we have declared, the
downloaded with its dependencies and installed them in our project folder.

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.

If we are on Windows, it's as simple as doing:

composer install

Note: Logically, that command won't work for you if you haven't installed it previously.
Composer.

Remember that in Windows Composer is installed globally, so it works from


the terminal in any folder of your system. You will simply place yourself in the folder of your
project and you will run the command 'composer install' to download and install dependencies.

If we are on Linux/Mac and we have installed Composer locally to a


project.It will be something like:

php composer.phar install

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

the global command can be:

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.

Returning to the command again

php composer.phar install

To explain it a bit, we can say that the program that is running is


composer.phar is the PHP executable. However, if you do not place php in front of it, the system
it is also smart to know that .phar files need to be run under the PHP interpreter.
Logically, you must have PHP installed on your system and it must be globally available for
that, being in your project folder, the terminal is able to know where it is.
PHP executable. In that command, you call composer.phar which is an executable file.
written in PHP and then you are telling Composer to install the dependencies.

Updating dependencies with Composer


Once you have the dependencies installed, if you want to update them, or if you have added
dependencies to your JSON file, you will make a command like this:

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.

Use the packages installed by Composer


Aside from greatly simplifying the download and installation of dependencies, Composer allows you to
provides an 'autoload' system for the classes that make up those libraries that you are
using.

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.

This article is the work of Miguel Angel Alvarez


It was first published on 21/11/2014
Available online athttp://desarrolloweb.com/articles/using-composer.html

The provided text is a URL and cannot be translated as it does not contain text. Page 17 of 28
Composer Tutorial

Setup of a PHP project with


composer.json

Explanations about the content of the JSON file of a project to use


Composer as a dependency manager.

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 composer.json scheme


The schema of a JSON defines the structure of the document as well as the values.
possible that have each of their fields. The specific address where you can find the
you can find the complete description of the schema of the composer.json at this URL
documentation

Unable to access the specified URL to fetch content for translation.

Fields that describe your project


Let's now look at a series of fields to provide information about us as developers.

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

A URL of the project's website.

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": [

Miguel Angel Alvarez

algo@desarrolloweb.com

http://www.desarrolloweb.com

Project Manager

},

Alvaro Martínez

algo@escuela.it

http://www.school.it

Beta tester

Define the dependencies


At the level of developing our own applications, the most important field where
we must focus on the definition of the dependencies, as well as the versions that
We wish for each of those dependencies to be installed or updated.

require:

No text provided for translation. Page 19 of 28


Composer Tutorial

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.

To find other possibilities, please consult the Composer documentation, in these


links:

Create links to dependent packages


Define the accepted versions

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.

The provided text is a URL and cannot be translated. Page 20 of 28


Composer tutorial

This article is the work of Miguel Angel Alvarez


It was first published on 12/12/2014
Available online athttp://desarrolloweb.com/articulos/setup-proyecto-php-composer-
Input text is not provided for translation.

The provided text is a URL and cannot be translated. Page 21 of 28


Composer Tutorial

Autoloading classes with Composer

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.

Obviously, when you install a dependency, a library, a class, or any code of


third parties in general, is because you want to use it within your PHP code. If you install a library to
You will need to know which folder you put it in and what the files are called.
code that you need to include, but if you do it from this dependency management system
You can save yourself the organizational work thanks to the class autoloading with Composer.

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.

Use an installed dependency


Actually, once autoload.php is loaded, we don't have much more to do. Simply, when
classes are needed (of object-oriented programming) because objects are instantiated or
make use of your static methods, these will be available to us.

Keep in mind that packagist dependencies are organized by namespaces in PHP, so


that when using the classes you will have to do the corresponding 'use', or write the
complete namespace where your class is.

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".

new League\Plates\Engine($raiz . '../data/templates');

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;

new Engine($raiz . '../data/templates');

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.

Set up the class autoloading system


The process described earlier is the basic work we will have to do to load the
libraries, in an agile way, thanks to Composer. But it could be necessary for our
applications to configure the automatic class loading system. In most cases, it will not be
necessary, but it can be useful if we want to take advantage of Composer's autoload
to automatically load the classes of our own project.

Unable to access the URL provided. Page 23 of 28


Composer Tutorial

To this end, a new field called "autoload" is defined in thecomposer.json file.

This field allows us to specify a namespace and the classes that are behind it.
namespace.

"autoload": {

"psr-4": {"MiNamespace\\": "mi_carpeta/"}

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.

This step is as simple as issuing the command:

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.

Configure the autoload system at runtime

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 = require 'vendor/autoload.php';

$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.

Invalid input. Please provide text that needs to be translated. Page 24 of 28


Composer Tutorial

You can find more information in the composer documentation, on the page of
autoloading in theComposer Manual.

This article is the work of Miguel Angel Alvarez


It was first published on 26/06/2018.
Available online atThe provided text is a URL and does not contain any translatable text.

The provided text is a URL and does not contain content to translate. Page 25 of 28
Composer Tutorial

Common Problems and Errors with


Composer

An article in which we see the problems we have encountered in


Composing in the day-to-day work and the solutions.

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)

Remember that at DesarrolloWeb.com we have made aComposer Manualwhat covers the


most basic aspects of its use and configuration. If you are not familiar with Composer and work with PHP
You must learn right now!

Keep composer updated


Aside from updating the dependencies, remember to update Composer itself. One of the
the first recommendations they offer you in the Composer guide is that in the face of any
make sure you are running the latest version of the software first. It
you get with an auto-update command.

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:

./composer.json does not contain valid JSON

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.

PHP memory limit


If your composer.json declares many dependencies, you may need to increase the memory of
the PHP processes. The error you will see is similar to this:

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.

What is my php.ini when I work from the command line?


It's a typical question. If you're working with Composer, you'll do it with the command 'composer'.
in your operating system terminal. In that case, you might be working with a php.ini
different from your PHP when it works on Apache.

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.

Increase the time of the composer process


Unable to access external content such as URLs. Page 27 of 28
Composer Tutorial

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:

COMPOSER_PROCESS_TIMEOUT=3600 composer install

In Composer's own documentation, you will find an excellentresolution guide


problems (in English) in which you will surely respond to many other situations. I
I will be adding other problems that I encounter to this list, for now this is
All right! If your problem is not on the list, send us the solution when you find it!

This article is the work of Miguel Angel Alvarez


It was first published on 01/05/2015
Available online athttp://desarrolloweb.com/articles/problems-solutions-
composer.html

Unable to access the content of the provided URL. Page 28 of 28

You might also like