Introduction
Composer is a popular PHP dependency management tool, mainly used to promote the installation and update of project dependencies. It will check other software packages that a specific project depends on using the appropriate version according to the project requirements and install it for you.
In this tutorial, you will install and start using Composer on an Ubuntu 18.04 system.
To complete this tutorial, you need:
sudo
command has been set up, and the firewall has been turned on. Students who don’t have a server can buy it from here, but I personally recommend you to use the free Tencent Cloud Developer Lab for experimentation, and then buy server.Before downloading and installing Composer, you need to make sure that your server has all dependencies installed.
First, run the following command to update the package manager cache:
sudo apt update
Now, let's install the dependencies. We need curl
to download Composer and php-cli
to install and run it. The php-mbstring
package is necessary to provide functionality for the library we will use. It is used by git
Composer to download project dependencies, and to extract compressed packages by unzip
. You can install everything with the following command:
sudo apt install curl php-cli php-mbstring git unzip
After installing the prerequisites, we can install Composer ourselves.
Composer provides an [installer] (https://getcomposer.org/installe) written in PHP. We will download it, verify if it is damaged, and then use it to install Composer.
Make sure you are in your home directory, then use curl
to retrieve the installer:
cd ~
curl -sS https://getcomposer.org/installer -o composer-setup.php
Next, verify that the installer matches the SHA-384hash of the latest installer found on the Composer Public Keys / Signatures page. Copy the hash from that page and store it as a shell variable:
HASH=544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061
Make sure to replace the highlighted value with the latest hash.
Now execute the following PHP script to verify that the installation script can run safely:
php -r "if (hash_file('SHA384', 'composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
You will see the following output.
Installer verified
If you see Installer corrupt
, then you need to download the installation script again and double-check whether you are using the correct hash. Then run the command to verify the installer again. Once you have a verified installer, you can continue.
To install composer
globally, use the following command, which will download and install Composer as a system-wide command named composer
located in /usr/local/bin
:
sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer
You will see the following output:
All settings correct for using Composer
Downloading...
Composer(version 1.6.5) successfully installed to:/usr/local/bin/composer
Use it: php /usr/local/bin/composer
To test your installation, run:
composer
You will see this output shows the Composer version and parameters.
______
/ ____/___ ____ ___ ____ ____ ________ _____
/// __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___///___//_////////_///_/(__ ) __/ /
\____ /\____/_//_//_/.___/\____/____/\___/_//_/
Composer version 1.6.52018-05-0411:44:59
Usage:
command [options][arguments]
Options:-h,--help Display this help message
- q,--quiet Do not output any message
- V,--version Display this application version
- - ansi Force ANSI output
- - no-ansi Disable ANSI output
- n,--no-interaction Do not ask any interactive question
- - profile Display timing and memory usage information
- - no-plugins Whether to disable plugins.-d,--working-dir=WORKING-DIR If specified, use the given directory as working directory.-v|vv|vvv,--verbose Increase the verbosity of messages:1for normal output,2for more verbose output and 3for debug
...
This will verify that Composer has been successfully installed on the system and can be used system-wide.
**Note: **If you want to have a Composer executable file for each project hosted on this server, you can install it locally on a per project basis. Users of NPM will be familiar with this method. This method is also useful when your system users do not have the right to install software on the system.
To do this, use the command php composer-setup.php
. This will generate a file in the current directory with composer.phar
, which can be used with ./composer.phar command
.
Now let's look at using Composer to manage dependencies.
PHP projects usually rely on external libraries, and managing these dependencies and their versions can be tricky. Composer solves this problem by tracking your dependencies and making it easy for others to install them.
To use Composer in your project, you need a composer.json
file. The composer.json
file tells Composer which dependencies you need to download for the project and which versions of each package are allowed to be installed. This is very important to maintain project consistency and avoid installing unstable versions that may cause backward compatibility issues.
You don't need to create this file manually-it's easy to run into syntax errors when doing this. When composer.json
uses the require
command to add dependencies to the project, Composer will automatically generate a file. You can add other dependencies in the same way without manually editing this file.
The process of using Composer to install a package as a dependency in a project includes the following steps:
composer require
to include dependencies in the composer.json
file and install the package.Let's try it with the demo application.
The goal of this application is to convert a given sentence into a URL friendly string-slug. This is usually used to convert page titles into URL paths (like the last part of the URL in this tutorial).
Let's start by creating a directory for the project. We call it slugify:
cd ~
mkdir slugify
cd slugify
Now is the time to search Packagist.org for a package that can help us generate slug. If you search for the word "slug" on Packagist, you will get results similar to this:
You will see two numbers on the right side of each package in the list. The number at the top indicates the number of installations of the package, and the number at the bottom indicates the number of times the package has been starred on GitHub. You can reorder the search results based on these numbers (look for the two icons on the right side of the search bar). Generally speaking, packages with more devices and more stars tend to be more stable because many people use them. It is also important to check the relevance of the package description to make sure it is what you need.
We need a simple string-to-slug converter. From the search results, the cocur/slugify
package seems to be a good match, with a reasonable number of installations and stars. (The package is deeper than the screenshot shows.)
The packages on Packagist have a vendor name and a package name. Each package has a unique identifier (namespace) in the format of vendor/package
that GitHub uses for its repositories. The library we are installing uses the cocur/slugif
namespace. You need the namespace to request packages in the project.
Now that you know exactly which package to install, run composer require
to include it as a dependency and generate a composer.json
file for the project:
composer require cocur/slugify
When Composer downloads the dependencies, you will see this output:
Using version ^3.1for cocur/slugify
. /composer.json has been created
Loading composer repositories withpackage information
Updating dependencies(including require-dev)
Package operations:1 install,0 updates,0 removals
- Installing cocur/slugify(v3.1):Downloading(100%)
Writing lock file
Generating autoload files
As you can see from the output, Composer automatically decides which version of the package to use. If you check the project directory now, it will contain two new files: composer.json
and composer.lock
, and a vendor
directory:
ls -l
total 12-rw-rw-r--1 sammy sammy 59 Jul 1116:40 composer.json
- rw-rw-r--1 sammy sammy 2934 Jul 1116:40 composer.lock
drwxrwxr-x 4 sammy sammy 4096 Jul 1116:40 vendor
The composer.lock
file is used to store information about the installed version of each package and to ensure that the same version is used when others clone your project and install its dependencies. The vendor
directory is where the project dependencies are located. The vendor
folder does not need to be submitted to version control-you only need to include the composer.json and composer.lock files.
When installing a project that already contains a composer.json
file, please run composer install
to download the project's dependencies.
Let's take a look at the version restrictions. If you check the contents of the composer.json
file, you will see the following:
cat composer.json
{" require":{"cocur/slugify":"^3.1"}}
sam
You may notice the special character ^
before the version number of composer.json
. Composer supports several different constraints and formats to define the required package version in order to provide flexibility while keeping the project stable. After [Semantic Versioning] (http://semver.org/), the caret (^
) operator used in the automatic generation of the composer.json
file is the recommended operator for maximum interoperability. In this case, it defines 3.1 as the minimum compatible version and allows updates to any future version below 4.0.
Generally speaking, you do not need to tamper with the version constraints in the composer.json
file. However, some situations may require you to edit constraints manually-for example, when you release a major new version of a required library and you want to upgrade, or when the library you want to use does not follow semantic version control.
Here are some examples to help you better understand how Composer version constraints work:
Constraints | Meaning | Allowed example versions |
---|---|---|
^ 1.0 | > = 1.0 <2.0 | 1.0,1.2.3,1.9.9 |
^ 1.1.0 | > = 1.1.0 <2.0 | 1.1.0,1.5.6,1.9.9 |
〜1.0 | > = 1.0 <2.0.0 | 1.0,1.4.1,1.9.9 |
〜1.0.0 | > = 1.0.0 <1.1 | 1.0.0,1.0.4,1.0.9 |
1.2.1 | 1.2.1 | 1.2.1 |
1. * | > = 1.0 <2.0 | 1.0.0,1.4.5,1.9.9 |
1.2 。* | > = 1.2 <1.3 | 1.2.0,1.2.3,1.2.9 |
For a more in-depth view of Composer version constraints, please refer to Official Documentation.
Next, let's see how to use Composer to automatically load dependencies.
Since PHP itself does not automatically load classes, Composer provides an automatic loading script that you can include in your project to automatically load it for free. This makes it easier to use dependencies.
The only thing you need to do is to include the vendor/autoload.php
file in the PHP script before any classes are instantiated. When you add the first dependency, Composer will automatically generate this file.
Let's try it in our app. Create the file test.php
and open it in a text editor:
nano test.php
Add the following code, which imports the vendor/autoload.php
file, loads the cocur/slugify
dependency, and uses it to create a slug:
<? php
require __DIR__ .'/vendor/autoload.php';
use Cocur\Slugify\Slugify;
$slugify =newSlugify();
echo $slugify->slugify('Hello World, this is a long sentence and I need to make a slug from it!');
Save the file and exit the editor.
Now run the script:
php test.php
This will produce the output hello-world-this-is-a-long-sentence-and-i-need-to-make-a-slug-from-it
.
When a new version appears, the dependencies need to be updated, so let's see how to deal with it.
Whenever you want to update project dependencies to a newer version, run the following update
command:
composer update
This will check for newer versions of required libraries in the project. If a newer version is found and it is compatible with the version constraints defined in the composer.json
file, Composer will replace the previously installed version. The composer.lock
file will be updated to reflect these changes.
You can also update one or more specific libraries by specifying as follows:
composer update vendor/package vendor2/package2
Be sure to check the composer.json
and composer.lock
files after updating your dependencies, so that others can install these updated versions.
Composer is a powerful tool that every PHP developer should have in their utility belt. In this tutorial, you installed Composer and used it in a simple project. You now know how to install and update dependencies.
In addition to providing a simple and reliable way to manage project dependencies, it also establishes a new de facto standard for sharing and discovering PHP packages created by the community.
For more Ubuntu tutorials, please go to [Tencent Cloud + Community] (https://cloud.tencent.com/developer?from=10680) to learn more.
Reference: "How To Install and Use Composer on Ubuntu 18.04"
Recommended Posts