介绍 (Introduction)
Composer is a popular dependency management tool for PHP, created mainly to facilitate installation and updates for project dependencies. It will check which other packages a specific project depends on and install them for you, using the appropriate versions according to the project requirements. Composer is also commonly used to bootstrap new projects based on popular PHP frameworks, such as Symfony and Laravel.
Composer是一种流行PHP依赖性管理工具,主要用于促进项目依赖性的安装和更新。 它将检查特定项目依赖的其他软件包,并根据项目要求使用适当的版本为您安装它们。 Composer通常还用于引导基于流行PHP框架(例如Symfony和Laravel)的新项目。
In this tutorial, you’ll install and get started with Composer on an Ubuntu 20.04 system.
在本教程中,您将在Ubuntu 20.04系统上安装Composer并开始使用它。
先决条件 (Prerequisites)
In order to follow this guide, you will need access to an Ubuntu 20.04 server as a non-root sudo
user, and a firewall enabled on your server. To set this up, you can follow our initial server setup guide for Ubuntu 20.04.
为了遵循本指南,您将需要以非root用户sudo
用户的身份访问Ubuntu 20.04服务器,并在服务器上启用防火墙。 要进行设置,您可以遵循我们的Ubuntu 20.04初始服务器设置指南 。
第1步-安装PHP和其他依赖项 (Step 1 — Installing PHP and Additional Dependencies)
In addition to dependencies that should be already included within your Ubuntu 20.04 system, such as git
and curl
, Composer requires php-cli
in order to execute PHP scripts in the command line, and unzip
to extract zipped archives. We’ll install these dependencies now.
除了应该已经包含在Ubuntu 20.04系统中的依赖项(例如git
和curl
,Composer还需要php-cli
才能在命令行中执行PHP脚本,并unzip
以提取压缩的存档。 现在,我们将安装这些依赖项。
First, update the package manager cache by running:
首先,通过运行以下命令更新程序包管理器缓存:
- sudo apt update sudo apt更新
Next, run the following command to install the required packages:
接下来,运行以下命令以安装所需的软件包:
- sudo apt install php-cli unzip 须藤apt install php-cli unzip
You will be prompted to confirm installation by typing Y
and then ENTER
.
将提示您通过键入Y
,然后按ENTER
确认安装。
Once the prerequisites are installed, you can proceed to installing Composer.
安装必备组件后,即可继续安装Composer。
第2步-下载并安装Composer (Step 2 — Downloading and Installing Composer)
Composer provides an installer script written in PHP. We’ll download it, verify that it’s not corrupted, and then use it to install Composer.
Composer提供了用PHP编写的安装程序脚本。 我们将下载它,确认它没有损坏,然后使用它来安装Composer。
Make sure you’re in your home directory, then retrieve the installer using curl
:
确保您位于主目录中,然后使用curl
检索安装程序:
- cd ~ 光盘〜
- curl -sS https://getcomposer.org/installer -o composer-setup.php curl -sS https://getcomposer.org/installer -o composer-setup.php
Next, we’ll verify that the downloaded installer matches the SHA-384 hash for the latest installer found on the Composer Public Keys / Signatures page. To facilitate the verification step, you can use the following command to programmatically obtain the latest hash from the Composer page and store it in a shell variable:
接下来,我们将验证下载的安装程序是否与Composer公钥/签名页面上找到的最新安装程序的SHA-384哈希匹配。 为了简化验证步骤,您可以使用以下命令以编程方式从Composer页面获取最新哈希并将其存储在shell变量中:
- HASH=`curl -sS https://composer.github.io/installer.sig` HASH =`curl -sS https:// composer.github.io / installer.sig`
If you want to verify the obtained value, you can run:
如果要验证所获得的值,可以运行:
- echo $HASH 回声$ HASH
Output
e0012edf3e80b6978849f5eff0d4b4e4c79ff1609dd1e613307e16318854d24ae64f26d17af3ef0bf7cfb710ca74755a
Now execute the following PHP code, as provided in the Composer download page, to verify that the installation script is safe to run:
现在执行Composer 下载页面中提供的以下PHP代码,以验证安装脚本可以安全运行:
- php -r "if (hash_file('SHA384', 'composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" php -r“ if(hash_file('SHA384','composer-setup.php')==='$ HASH'){回声'安装程序已验证';}其他{回声'安装程序已损坏';取消链接('composer-setup .php');}回显PHP_EOL;“
You’ll see the following output:
您将看到以下输出:
Installer verified
If the output says Installer corrupt
, you’ll need to download the installation script again and double check that you’re using the correct hash. Then, repeat the verification process. When you have a verified installer, you can continue.
如果输出显示Installer corrupt
,则需要再次下载安装脚本,并再次检查您使用的哈希值是否正确。 然后,重复验证过程。 安装程序经过验证后,可以继续。
To install composer
globally, use the following command which will download and install Composer as a system-wide command named composer
, under /usr/local/bin
:
要全局安装composer
,请使用以下命令,该命令将在/usr/local/bin
下以名为composer
的系统级命令下载并安装Composer:
sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer
sudo php composer-setup.php --install-dir = / usr / local / bin --filename = composer
You’ll see output similar to this:
您将看到类似于以下的输出:
Output
All settings correct for using Composer
Downloading...
Composer (version 1.10.5) successfully installed to: /usr/local/bin/composer
Use it: php /usr/local/bin/composer
To test your installation, run:
要测试您的安装,请运行:
- composer 作曲家
Output
______
/ ____/___ ____ ___ ____ ____ ________ _____
/ / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
/_/
Composer version 1.10.5 2020-04-10 11:44:22
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.
--no-cache Prevent use of the cache
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
...
This verifies that Composer was successfully installed on your system and is available system-wide.
这将验证Composer已成功安装在您的系统上并且在系统范围内可用。
Note: If you prefer to have separate Composer executables for each project you host on this server, you can install it locally, on a per-project basis. This method is also useful when your system user doesn’t have permission to install software system-wide.
注意:如果您希望在此服务器上托管的每个项目都具有单独的Composer可执行文件,则可以在每个项目的基础上在本地安装它。 当您的系统用户无权在系统范围内安装软件时,此方法也很有用。
To do this, use the command php composer-setup.php
. This will generate a composer.phar
file in your current directory, which can be executed with php composer.phar
.
为此,请使用命令php composer-setup.php
。 这将在当前目录中生成一个composer.phar
文件,可以使用php composer.phar
执行该文件。
Now let’s look at using Composer to manage dependencies.
现在让我们看一下使用Composer来管理依赖项。
步骤3 —在PHP项目中使用Composer (Step 3 — Using Composer in a PHP Project)
PHP projects often depend on external libraries, and managing those dependencies and their versions can be tricky. Composer solves that problem by keeping track of project versions and dependencies, while also facilitating the process of finding, installing, and updating packages that are required by a project.
PHP项目通常依赖于外部库,并且管理那些依赖关系及其版本可能很棘手。 Composer通过跟踪项目版本和依赖性来解决该问题,同时还简化了查找,安装和更新项目所需软件包的过程。
In order to use Composer in your project, you’ll need a composer.json
file. The composer.json
file tells Composer which dependencies it needs to download for your project, and which versions of each package are allowed to be installed. This is extremely important to keep your project consistent and avoid installing unstable versions that could potentially cause backwards compatibility issues.
为了在您的项目中使用Composer,您需要一个composer.json
文件。 composer.json
文件告诉Composer您需要为项目下载哪些依赖项,以及允许安装每个软件包的哪个版本。 这对于保持项目的一致性并避免安装可能导致向后兼容性问题的不稳定版本非常重要。
You don’t need to create this file manually - it’s common to run into syntax errors when you do so. Composer offers an interactive way to create a new composer.json
file based on the user’s input, which is a good choice if you plan on sharing your project later as a public package on Packagist. Composer also auto-generates a barebones composer.json
file when you run a composer require
command to include a dependency in a newly created project.
您不需要手动创建此文件-这样做时经常会遇到语法错误。 Composer提供了一种基于用户输入的交互式方式来创建新的composer.json
文件,如果您打算以后作为Packagist上的公共包共享项目,则这是一个不错的选择。 当您运行composer require
命令在新创建的项目中包括依赖项时,Composer还会自动生成准系统的composer.json
文件。
The process of using Composer to install a package as dependency in a project involves the following steps:
使用Composer在项目中将软件包安装为依赖项的过程涉及以下步骤:
- Identify what kind of library the application needs. 确定应用程序需要哪种库。
Research a suitable open source library on Packagist.org, the official package repository for Composer.
在Packagist.org (Composer的官方软件包存储库)上研究合适的开源库。
- Choose the package you want to depend on. 选择您要依赖的软件包。
Run
composer require
to include the dependency in thecomposer.json
file and install the package.运行
composer require
将该依赖项包含在composer.json
文件中并安装该软件包。
Let’s try this out with a demo application.
让我们通过演示应用程序进行尝试。
The goal of this application is to transform a given sentence into a URL-friendly string - a slug. This is commonly used to convert page titles to URL paths (like the final portion of the URL for this tutorial).
该应用程序的目标是将给定的句子转换为URL友好的字符串-slug 。 这通常用于将页面标题转换为URL路径(例如本教程URL的最后部分)。
Let’s start by creating a directory for our project. We’ll call it slugify:
让我们从为项目创建目录开始。 我们称它为Slugify :
- cd ~ 光盘〜
- mkdir slugify mkdir弹头
- cd slugify cd slugify
Although not required, you could now run a composer init
command to create a detailed composer.json
file for your project. Because our project’s only objective is to demonstrate how to install dependencies with Composer, we’ll use a simpler composer.json
file that will be auto-generated when we require our first package.
尽管不是必需的,但是您现在可以运行composer init
命令来为您的项目创建详细的composer.json
文件。 因为我们项目的唯一目的是演示如何使用Composer安装依赖项,所以我们将使用一个更简单的composer.json
文件,该文件将在我们需要第一个软件包时自动生成。
Now it’s time to search Packagist.org for a package that can help us generate slugs. If you search for the term “slug” on Packagist, you’ll get a result similar to this:
现在是时候来搜索Packagist.org一个包,可以帮助我们产生蛞蝓 。 如果在Packagist上搜索“ slug”一词,则会得到类似以下结果:
You’ll see two numbers on the right side of each package in the list. The number on the top represents how many times the package was installed via Composer, and the number on the bottom shows how many times a package was starred on GitHub. Generally speaking, packages with more installations and more stars tend to be more stable, since so many people are using them. It’s also important to check the package description for relevance to make sure it’s what you need.
您会在列表中每个包装的右侧看到两个数字。 顶部的数字表示通过Composer安装软件包的次数,底部的数字表示在GitHub上为软件包加注星标的次数。 一般而言,具有更多安装和更多星形的软件包往往更稳定,因为有很多人在使用它们。 检查软件包说明的相关性以确保它是您所需要的也很重要。
We need a string-to-slug converter. From the search results, the package cocur/slugify
, which appears as the first result in that page, seems to be a good match, with a reasonable amount of installations and stars.
我们需要一个字符串转换器。 从搜索结果中可以看到,软件包cocur/slugify
出现在该页面的第一个结果中,看起来非常匹配,并且安装量和星级都相当合理。
Packages on Packagist have a vendor name and a package name. Each package has a unique identifier (a namespace) in the same format GitHub uses for its repositories: vendor/package
. The library we want to install uses the namespace cocur/slugify
. You need a package’s namespace in order to require it in your project.
Packagist上的软件包具有供应商名称和软件包名称。 每个软件包都有一个唯一的标识符(名称空间),其标识符与GitHub用于其存储库的格式相同: vendor / package
。 我们要安装的库使用名称空间cocur/slugify
。 您需要包的名称空间才能在项目中使用它。
Now that you know exactly which package you want to install, you can run composer require
to include it as a dependency and also generate the composer.json
file for your project. One thing that is important to notice when requiring packages is that Composer tracks both application-level dependencies as well as system-level dependencies. System-level dependencies are important to indicate which PHP modules a package relies on. In the case of the cocur/slugify
package, it requires a PHP module that we haven’t installed yet.
现在,您已经知道要安装的软件包,可以运行composer require
将其包含为依赖项,并为您的项目生成composer.json
文件。 需要软件包时需要注意的一件事是Composer既跟踪应用程序级别的依赖关系,又跟踪系统级别的依赖关系。 系统级别的依赖关系对于指示软件包依赖哪个PHP模块很重要。 对于cocur/slugify
软件包,它需要一个我们尚未安装PHP模块。
When a required package relies on a system library that is currently not installed on your server, you will get an error telling which requirement is missing:
当所需的软件包依赖于服务器上当前未安装的系统库时,您将收到一条错误消息,指出缺少哪些要求:
- composer require cocur/slugify 作曲者需要共处
Output
Using version ^4.0 for cocur/slugify
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Installation request for cocur/slugify ^4.0 -> satisfiable by cocur/slugify[v4.0.0].
- cocur/slugify v4.0.0 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
...
To solve the system dependency problem, we can search for the missing package using apt search
:
为了解决系统依赖性问题,我们可以使用apt search
缺少的软件包:
- apt search mbstring apt搜索mbstring
Output
Sorting... Done
Full Text Search... Done
php-mbstring/focal 2:7.4+75 all
MBSTRING module for PHP [default]
php-patchwork-utf8/focal 1.3.1-1 all
UTF-8 strings handling for PHP
php7.4-mbstring/focal 7.4.3-4ubuntu1 amd64
MBSTRING module for PHP
After locating the correct package name, you can use apt
once again to install the system dependency:
找到正确的程序包名称后,可以再次使用apt
来安装系统依赖项:
sudo apt install php-mbstring
sudo apt安装php-mbstring
Once the installation is finished, you can run the composer require
command again:
安装完成后,您可以再次运行composer require
命令:
- composer require cocur/slugify 作曲者需要共处
Output
Using version ^4.0 for cocur/slugify
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
- Installing cocur/slugify (v4.0.0): Downloading (100%)
Writing lock file
Generating autoload files
As you can see from the output, Composer automatically decided which version of the package to use. If you check your project’s directory now, it will contain two new files: composer.json
and composer.lock
, and a vendor
directory:
从输出中可以看到,Composer会自动决定要使用哪个版本的软件包。 如果现在检查项目的目录,它将包含两个新文件: composer.json
和composer.lock
以及vendor
目录:
- ls -l ls -l
Output
total 12
-rw-rw-r-- 1 sammy sammy 59 May 4 13:56 composer.json
-rw-rw-r-- 1 sammy sammy 3229 May 4 13:56 composer.lock
drwxrwxr-x 4 sammy sammy 4096 May 4 13:56 vendor
The composer.lock
file is used to store information about which versions of each package are installed, and ensure the same versions are used if someone else clones your project and installs its dependencies. The vendor
directory is where the project dependencies are located. The vendor
folder shouldn’t be committed into version control - you only need to include the composer.json and composer.lock files.
composer.lock
文件用于存储有关安装每个软件包的版本的信息,并确保在其他人克隆您的项目并安装其依赖项时确保使用相同的版本。 vendor
目录是项目依赖项所在的位置。 vendor
文件夹不应提交到版本控制中-您只需要包括composer.json和composer.lock文件。
When installing a project that already contains a composer.json
file, run composer install
in order to download the project’s dependencies.
当安装已经包含composer.json
文件的项目时,请运行composer install
来下载项目的依赖项。
Let’s take a quick look at version constraints. If you check the contents of your composer.json
file, you’ll see something like this:
让我们快速看一下版本约束。 如果检查composer.json
文件的内容,则会看到类似以下内容:
- cat composer.json 猫composer.json
Output
{
"require": {
"cocur/slugify": "^4.0"
}
}
You might notice the special character ^
before the version number in composer.json
. Composer supports several different constraints and formats for defining the required package version, in order to provide flexibility while also keeping your project stable. The caret (^
) operator used by the auto-generated composer.json
file is the recommended operator for maximum interoperability, following semantic versioning. In this case, it defines 4.0 as the minimum compatible version, and allows updates to any future version below 5.0.
您可能会在composer.json
的版本号之前注意到特殊字符^
。 Composer支持几种不同的约束和格式来定义所需的软件包版本,以便在保持项目稳定的同时提供灵活性。 自动生成的composer.json
文件使用的插入符( ^
)是建议的运算符,它遵循语义版本控制以实现最大的互操作性。 在这种情况下,它将4.0定义为最低兼容版本,并允许更新到低于5.0的任何将来版本。
Generally speaking, you won’t need to tamper with version constraints in your composer.json
file. However, some situations might require that you manually edit the constraints–for instance, when a major new version of your required library is released and you want to upgrade, or when the library you want to use doesn’t follow semantic versioning.
一般来说,您无需篡改composer.json
文件中的版本限制。 但是,在某些情况下,可能需要手动编辑约束-例如,当发布所需库的主要新版本并且要升级时,或者要使用的库不遵循语义版本控制时。
Here are some examples to give you a better understanding of how Composer version constraints work:
以下是一些示例,可以使您更好地了解Composer版本约束的工作方式:
Constraint | Meaning | Example Versions Allowed |
---|---|---|
^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 |
约束 | 含义 | 允许的示例版本 |
---|---|---|
^ 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, see the official documentation.
有关Composer版本限制的更深入的信息,请参见官方文档 。
Next, let’s look at how to load dependencies automatically with Composer.
接下来,让我们看看如何使用Composer自动加载依赖项。
步骤4 —包括自动加载脚本 (Step 4 — Including the Autoload Script)
Since PHP itself doesn’t automatically load classes, Composer provides an autoload script that you can include in your project to get autoloading working for your project. This file is automatically generated by Composer when you add your first dependency.
由于PHP本身不会自动加载类,因此Composer提供了一个自动加载脚本,您可以将其包含在项目中,以使自动加载可用于您的项目。 添加第一个依赖项时,此文件由Composer自动生成。
The only thing you need to do is include the vendor/autoload.php
file in your PHP scripts before any class instantiation.
您唯一需要做的是在任何类实例化之前,在PHP脚本中包含vendor/autoload.php
文件。
Let’s try it out in our demo application. Open a new file called test.php
in your text editor:
让我们在演示应用程序中尝试一下。 在文本编辑器中打开一个名为test.php
的新文件:
- nano test.php 纳米测试
Add the following code which brings in the vendor/autoload.php
file, loads the cocur/slugify
dependency, and uses it to create a slug:
添加以下代码,该代码将cocur/slugify
vendor/autoload.php
文件,加载cocur/slugify
依赖项,并使用它来创建一个slug:
<?php
require __DIR__ . '/vendor/autoload.php';
use Cocur\Slugify\Slugify;
$slugify = new Slugify();
echo $slugify->slugify('Hello World, this is a long sentence and I need to make a slug from it!');
Save the file and exit your editor.
保存文件并退出编辑器。
Now run the script:
现在运行脚本:
- php test.php php test.php
This produces the output hello-world-this-is-a-long-sentence-and-i-need-to-make-a-slug-from-it
.
这将产生输出hello-world-this-is-a-long-sentence-and-i-need-to-make-a-slug-from-it
。
Dependencies need updates when new versions come out, so let’s look at how to handle that.
新版本发布时,依赖项需要更新,因此让我们看一下如何处理。
步骤5 —更新项目依赖项 (Step 5 — Updating Project Dependencies)
Whenever you want to update your project dependencies to more recent versions, run the update
command:
每当您要将项目依赖项更新到最新版本时,请运行update
命令:
- composer update 作曲家更新
This will check for newer versions of the libraries you required in your project. If a newer version is found and it’s compatible with the version constraint defined in the composer.json
file, Composer will replace the previous version installed. The composer.lock
file will be updated to reflect these changes.
这将检查项目中所需的较新版本的库。 如果找到较新的版本,并且与composer.json
文件中定义的版本限制兼容,则Composer将替换以前安装的版本。 composer.lock
文件将被更新以反映这些更改。
You can also update one or more specific libraries by specifying them like this:
您还可以通过这样指定一个或多个特定库来更新它们:
composer update vendor/package vendor2/package2
作曲家更新供应商/程序包 vendor2 / package2
Be sure to check in your composer.json
and composer.lock
files within your version control system after you update your dependencies so that others can install these newer versions too.
更新依赖项后,请确保在版本控制系统中检入composer.json
和composer.lock
文件,以便其他人也可以安装这些较新的版本。
结论 (Conclusion)
Composer is a powerful tool that can greatly facilitate the work of managing dependencies in PHP projects. It provides a reliable way of discovering, installing, and updating PHP packages that a project depends on. In this guide, we saw how to install Composer, how to include new dependencies in a project, and how to update these dependencies once new versions are available.
Composer是一个功能强大的工具,可以极大地促进在PHP项目中管理依赖项的工作。 它提供了一种可靠的方式来发现,安装和更新项目所依赖PHP软件包。 在本指南中,我们了解了如何安装Composer,如何在项目中包括新的依赖项以及一旦有新版本可用后如何更新这些依赖项。
翻译自: https://www.digitalocean.com/community/tutorials/how-to-install-and-use-composer-on-ubuntu-20-04