[Transfer] Getting Started with Composer, Getting Started with Composer_PHP Tutorial

WBOY
Release: 2016-07-12 08:58:05
Original
669 people have browsed it

【Transfer】Getting started with Composer, getting started with composer

Java has Maven, Node.js has npm, and ROR has gem. Programmers of these languages ​​are happily using package management tools to accelerate When it comes to developing efficiency, PHPers are still in the dark of copy-paste. Before Composer, PHP had a miserable history of package management.

For a long time, if the application depends on third-party libraries, PHPer needs to copy the source code of these libraries, or install them through PEAR or PECL. If a third-party library depends on more third-party libraries, it will soon enter a black hole of dependencies. Until Composer appeared, PHPers saw the dawn of PHP package management.

The following will take creating an e-commerce website as an example to introduce how to use Composer.

Configuration file

When we start a project, we first give the project a name. Let’s call it Silk Road for the time being, codenamed silk. First, you need to write a Composer configuration file to describe the project. To do this, create a configuration file named composer.json in the root directory of the project. The content is as follows:

<code class="hljs dust"><span class="xml"><span class="hljs-comment"><!-- lang: js -->
<span class="hljs-expression">{
<span class="hljs-string">"name":             <span class="hljs-string">"meta/silk",
<span class="hljs-string">"description":      <span class="hljs-string">"another e-commerce website",
<span class="hljs-string">"keywords":         [<span class="hljs-string">"silk", <span class="hljs-string">"online shop", <span class="hljs-string">"good"],
<span class="hljs-string">"homepage":         <span class="hljs-string">"http://www.xxx.com ",
<span class="hljs-string">"time":             <span class="hljs-string">"2014-12-30",
<span class="hljs-string">"license":          <span class="hljs-string">"MIT",
<span class="hljs-string">"authors": [
    {
        <span class="hljs-string">"name":         <span class="hljs-string">"Elvis Lim",
        <span class="hljs-string">"email":        <span class="hljs-string">"elvis@xxx.com",
        <span class="hljs-string">"homepage":     <span class="hljs-string">"http://www.xxx.com",
        <span class="hljs-string">"role":         <span class="hljs-string">"Engineer"
    }<span class="xml">
]}
</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code>
Copy after login

If you are familiar with the JSON format, the above paragraph is self-explanatory. In fact, these key-value pairs are optional. In other words, you don’t have to write it at all. But if you want to package the project into a public package for release, then these still need to be written. It is never too much to give your package a name. Let’s go through the meaning of these key-value pairs.

<code class="hljs xml"><span class="hljs-comment"><!-- lang: js -->
"name":             "meta/silk",
</span></code>
Copy after login

name, indicates the name of the package. If you often hang out on Github, then the expression of this value must be very familiar. To explain, usually the package name contains two parts, separated by /. The front part of the diagonal bar represents the owner of the bag. Currently, most package authors like to use Github username as the value of this part. The part behind the diagonal bar represents the name of the package. Try to keep it simple and meaningful so that it is easy to remember and spread. In most cases, many people will name it after the Github code library name. Of course, in this case, it makes more sense for the code to exist on Github.

<code class="hljs xml"><span class="hljs-comment"><!-- lang: js -->
"description":      "another e-commerce website",
</span></code>
Copy after login

Application introduction, this part introduces the project as concisely as possible, don’t make it long. If you really have a lot to say, you can write it in the README.md file.

<code class="hljs xml"><span class="hljs-comment"><!-- lang: js -->
"keywords":         ["silk", "online shop", "good"],
</span></code>
Copy after login

The value of the keyword is a string array, which is used as metadata information to facilitate package search and discovery when it is published as a public library.

<code class="hljs xml"><span class="hljs-comment"><!-- lang: js -->
"homepage":         "http://www.xxx.com ",
</span></code>
Copy after login

Home page, you can put any page address you want.

<code class="hljs xml"><span class="hljs-comment"><!-- lang: js -->
"license": "MIT",
</span></code>
Copy after login

If you decide to release the package publicly, remember to choose an appropriate license. In this way, when other programmers reference the package, they can check the license to ensure that there are no legal problems.

<code class="hljs xml"><span class="hljs-comment"><!-- lang: js -->
 "authors":[{}]
</span></code>
Copy after login

The author field can contain an array of objects, which means multiple author information can be provided.

So far, it’s all information about the package itself. As an e-commerce website, being able to send emails and export orders to Excel tables is a basic requirement. At this time, it was natural to think of using existing libraries to implement these functions. To obtain these libraries, the simplest way is to search for these libraries, find the download address, download a zip package, then unzip it to the corresponding directory, and import the corresponding files according to the documentation. Using Composer, this process can be completed more automatically and elegantly. This is Composer's dependency management.

Dependency Management

Add a new field in the composer.json file: require. The value of this field is an object, also in the form of key-value pairs. Taking the two dependency locations mentioned above, the composer management method is written as follows:

<code class="hljs dust"><span class="xml"><span class="hljs-comment"><!-- lang: js -->
&ldquo;require&rdquo;: <span class="hljs-expression">{
<span class="hljs-string">"swiftmailer/swiftmailer": 5<span class="hljs-variable">.3<span class="hljs-variable">.*@<span class="hljs-variable">dev,
<span class="hljs-string">"phpoffice/phpexcel": <span class="hljs-string">"dev-master"
}</span></span></span></span></span></span></span></span></span></code>
Copy after login

Take swiftmailer as an example. swiftmailer/swiftmailer represents the package name, and 5.3.@dev represents the version information. What this means together is that the application we are going to develop depends on the 5.3. version of swiftmailer. Among them:

5.3.* means that you can use version 5.3.1 or 5.3.2. When obtaining it, composer will look for the latest version under version 5.3. The version number supports some broader constraints, such as >=1.0, >=1.0, <2.0. More specific information can be viewed at: http://docs.phpcomposer.com/01-basic-usage.md#The - require-Key

@dev indicates that the development version is available. Usually, a development version means an unstable version and is likely to contain bugs. Stability labels can apply to specific dependencies or globally.

Function-specific dependencies: By default, composer will only obtain stable versions. If we do not add @dev constraints in this example, and the 5.3.* versions are all development versions, then composer will report an error when obtaining, pointing out The modified version does not meet the requirements. If you are sure that there is no problem with this development version, you can let Composer get this development version by adding @dev.

Global stability settings: By setting the value of minimum-stability, you can tell Composer the global stability level of the package required by the dependencies of the currently developed project. Its values ​​include: dev, alpha, beta, RC, stable, stable is the default value.

At this point, the two dependencies have been added. We can run the Composer package update command to see the effect.

<code class="hljs xml"><span class="hljs-comment"><!-- lang: shell -->
composer install
</span></code>
Copy after login
Copy after login

After running successfully, you will find the vendor folder in the root directory, which contains the two package file codes we just listed.

require-dev

有时候,我们会发现,有些包依赖只会在开发过程中使用,正式发布的程序不需要这些包,这个时候,就需要用到另外一个键,即require-dev。例如,我们想用codeception进行单元测试,那么就可以通过require-dev引入这个开发环境下的依赖包:

<code class="hljs dust"><span class="xml"><span class="hljs-comment"><!-- lang: js -->
&ldquo;require-dev&rdquo;: <span class="hljs-expression">{
<span class="hljs-string">"codeception/codeception": <span class="hljs-string">"2.0.0 "
}</span></span></span></span></span></code>
Copy after login

加了这个依赖后,再运行下命令看看效果。

<code class="hljs xml"><span class="hljs-comment"><!-- lang: shell -->
composer install
</span></code>
Copy after login
Copy after login

自动加载

自此,composer已经帮我们把需要的库文件下载下来啦,接下去想到的就是如何引用这些库文件。最简单的方式就是require或者 include,但这就不够高大上了啊,需要花时间去库文件里查看需要引入哪些文件,费事而且容易出错。好在composer可以帮我们解决这个问题。那 就是autoload。

在运行完composer install命令后,怎么调用PHPExcel库呢?很简单,只要引入vendor目录下的autoload.php文件就可以了。可以在根目录下,建一个index.php文件,加入一下内容:

<code class="hljs php">
<span class="hljs-keyword">include &ldquo;vendor/autoload.php&rdquo;
<span class="hljs-variable">$excel = <span class="hljs-keyword">new PHPExcel();
var_dump(<span class="hljs-variable">$excel);
</span></span></span></span></code>
Copy after login

用浏览器访问一下这个页面,就会发现PHPExcel对象已经被成功创建啦,是不是很方便?

其实到目前为止,我们并没用在composer.json文件里加入autoload字段,那么什么时候需要加入呢? 那就是当我们想让composer帮我们自动加载我们自己定义的类的时候。例如,我们自己写了个订单管理类,取名OrderManager,放在lib目 录下的OrderManager.php文件里。内容如下:

<code class="hljs php">
<span class="hljs-class"><span class="hljs-keyword">class <span class="hljs-title">OrderManager
{
    <span class="hljs-keyword">public <span class="hljs-function"><span class="hljs-keyword">function <span class="hljs-title">test<span class="hljs-params">()
    {
        <span class="hljs-keyword">echo <span class="hljs-string">"hello";
    }
}
</span></span></span></span></span></span></span></span></span></span></code>
Copy after login

那么如何让composer帮我们自动加载这个类呢? 在composer.json里加入下面的内容:

<code class="hljs dust"><span class="xml"><span class="hljs-comment"><!-- lang: js -->
&ldquo;autoload&rdquo;:<span class="hljs-expression">{
    <span class="hljs-string">"files":[<span class="hljs-string">"lib/OrderManager.php"]
}</span></span></span></span></span></code>
Copy after login

files键对应的值是一个数组,数组元素是文件的路径,路径是相对于应用的根目录。加上上述内容后,运行命令:

<code class="hljs xml"><span class="hljs-comment"><!-- lang: js -->
composer dump-autoload
</span></code>
Copy after login

让composer重建自动加载的信息,完成之后,就可以在index.php里调用OrderManager类啦。

通过文件引入的方法虽然直观,但是很费劲,每个文件都得引入一次,实在不是好的解决办法。有没有更好的办法呢?尝试将autoload的值改成:

<code class="hljs xml"><span class="hljs-comment"><!-- lang: js -->
 "classmap":["lib"]
</span></code>
Copy after login

再此运行composer dump-autoload,尝试调用,依然能够成功创建OrderManager类。其实,classmap通过建立类到文件的对应关系,当程序需要 OrderManager类时,compoer的自动加载类通过查找OrderManager类所在的文件,然后再将改文件include进来。因此,这 又导致了一个问题,那就是每加一个新类,就需要运行一次composer dump-autoload来创建类到文件到对应关系,比files方法虽然好一点,但是还是很不够舒爽啊!于是,PSR-0出场了。先了解下什么是 PSR-0。

FIG组织制定的一组PHP相关规范,简称PSR,其中

PSR-0自动加载
PSR-1基本代码规范
PSR-2代码样式
PSR-3日志接口
PSR-4 自动加载

目前就这五个规范,乍一看,PSR-0和PSR-4是重复了,实际上,在功能上确实有所重复。区别在于PSR-4的规范比较干净,去除了兼容PHP 5.3以前版本的内容,有一点PSR-0升级版的感觉。当然,PSR-4也不是要完全替代PSR-0,而是在必要的时候补充PSR-0——当然,如果你愿 意,PSR-4也可以替代PSR-0。PSR-4可以和包括PSR-0在内的其他自动加载机制共同使用。

PSR-0规范的具体内容见:https://github.com/hfcorriez/fig-standards/blob/zh_CN/%E6%8E%A5%E5%8F%97/PSR-0.md
PSR-4规范的具体内容见:https://github.com/hfcorriez/fig-standards/blob/zh_CN/%E6%8E%A5%E5%8F%97/PSR-4-autoloader.md

简而言之,就是希望通过一组约定的目录,文件名,类名定义方式,来实现快速通过类查找到文件,然后包含进来,实现自动加载。
PSR-4和PSR-0最大的区别是对下划线(underscore)的定义不同。PSR-4中,在类名中使用下划线没有任何特殊含义。而PSR-0则规定类名中的下划线_会被转化成目录分隔符。

不管是PSR-0还是PSR-4,都要求有个命名空间,所以我们需要对OrderManager类进行一些小的修改,加上命名空间:

<code class="hljs php">
<span class="hljs-keyword">namespace <span class="hljs-title">SilkLib;
<span class="hljs-class"><span class="hljs-keyword">class <span class="hljs-title">OrderManager
{
    <span class="hljs-keyword">public <span class="hljs-function"><span class="hljs-keyword">function <span class="hljs-title">test<span class="hljs-params">()
    {
        <span class="hljs-keyword">echo <span class="hljs-string">"hello";
    }
 }
</span></span></span></span></span></span></span></span></span></span></span></span></code>
Copy after login

同时,文件夹的结构也要修改成:应用根目录\lib\SilkLib\OrderManager.php

然后修改composer.json里的autoload部分如下:

<code class="hljs dust"><span class="xml"><span class="hljs-comment"><!-- lang: js -->
"autoload":<span class="hljs-expression">{
    <span class="hljs-string">"psr-0":{
        <span class="hljs-string">"SilkLib":<span class="hljs-string">"lib/"
    }<span class="xml">
}
</span></span></span></span></span></span></span></code>
Copy after login

这里需要注意的是,SlikLib是命名空间,lib是目录名,他们的组合告诉composer,文件搜索是在:lib/SilkLib/ 目录下,而不是在 SilkLib/lib 目录下,这一点要特别注意,有点绕,容易弄错。

如果我们把命名空间改成 Slik\lib, 相应的目录结构要改成:应用根目录\lib\Silk\lib\OrderManager.php,autoload部分的写法相应的也要改成:

<code class="hljs dust"><span class="xml"><span class="hljs-comment"><!-- lang: js -->
"autoload":<span class="hljs-expression">{
    <span class="hljs-string">"psr-0":{
        <span class="hljs-string">"Silk\\lib":<span class="hljs-string">"lib/"
    }<span class="xml">
}
</span></span></span></span></span></span></span></code>
Copy after login

注意Silk\lib是双斜杆。好了,那我们试试再加一个类,然后不用运行composer dump-autoload命令,看看新类是否能加载上。在lib目录下,新增一个ShipManager.php文件,内容如下:

<code class="hljs php">
<span class="hljs-keyword">namespace <span class="hljs-title">Silk\<span class="hljs-title">lib;
<span class="hljs-class"><span class="hljs-keyword">class <span class="hljs-title">ShipManager
{
    <span class="hljs-keyword">public <span class="hljs-function"><span class="hljs-keyword">function <span class="hljs-title">test<span class="hljs-params">()
    {
        <span class="hljs-keyword">echo <span class="hljs-string">'hello ship class';
    }
}
</span></span></span></span></span></span></span></span></span></span></span></span></span></code>
Copy after login

尝试在index.php文件中调用:

<code class="hljs lasso">
<span class="hljs-variable">$orderMgr <span class="hljs-subst">= <span class="hljs-literal">new Silk<span class="hljs-subst">\lib<span class="hljs-subst">\OrderManager();
<span class="hljs-variable">$orderMgr<span class="hljs-subst">->test();
<span class="hljs-variable">$shipMgr <span class="hljs-subst">= <span class="hljs-literal">new Silk<span class="hljs-subst">\lib<span class="hljs-subst">\ShipManager();
<span class="hljs-variable">$shipMgr<span class="hljs-subst">->test();
</span></span></span></span></span></span></span></span></span></span></span></span></span></span></code>
Copy after login

运行成功,说明使用psr-0规范进行自动加载,比classmap更加方便。下面试试psr-4方式,整理下目录结构,改成:应用根目录\lib\OrderManager.php,修改命名空间为Silk, 修改autoload部分为:

<code class="hljs 1c">
<span class="hljs-string">"autoload":{
    <span class="hljs-string">"psr-4":{
        <span class="hljs-string">"Silk":<span class="hljs-string">"lib"
    }
}
</span></span></span></span></code>
Copy after login

尝试调用,发现报错Fatal error: Uncaught exception 'InvalidArgumentException' with message 'A non-empty PSR-4 prefix must end with a namespace separator. 提示要加上分隔符,那就加上吧:

<code class="hljs dust"><span class="xml"><span class="hljs-comment"><!-- lang: js -->
"autoload":<span class="hljs-expression">{
    <span class="hljs-string">"psr-4":{
        <span class="hljs-string">"Silk\\":<span class="hljs-string">"lib"
    }<span class="xml">
}
</span></span></span></span></span></span></span></code>
Copy after login

再次composer dump-autoload,运行测试,OK通过!

掌握require和autoload部分,其实就算Compoer入门啦,在详细的内容,可以通过查看composer文档来了解。Happy Coding!

原文转于:http://my.oschina.net/u/248080/blog/359008

感谢原著

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1104656.htmlTechArticle【转】Composer入门,composer入门 Java有Maven, Node.js有npm, ROR有gem, 这些语言的程序员在开心地使用包管理工具加速开发效率时,PHPer们还在复制...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!