"Go" composer Getting started, composer Getting started _php tutorials

Source: Internet
Author: User
Tags autoload composer install

"Go" composer Getting started, composer Getting started


Java has maven, node. JS has NPM, ROR has gems, these language programmers are happy to use package management tools to accelerate development efficiency, phper are still in the dark copy and paste. PHP before composer, the history of package management.

For a long period of time, if the application relies on third-party libraries, Phper needs to copy the source code of these libraries, or install them through pear, pecl. If a third-party library relies on more third-party libraries, it will quickly enter a dependent black hole. Until composer appeared, Phper saw the dawn of the package management that belonged to PHP.

The following is an example of creating an e-commerce website that describes how to use composer.

Configuration file

When we start a project, we will first give the project a name, we call the Silk Road bar, code silk. First of all to write a composer configuration file to describe the project, for this, in the root directory of the project, the establishment of a file named Composer.json configuration file. The contents are as follows:


    {"Name":"Meta/silk", "description":  "another E-commerce website", " keywords ": [" online shop ", " good "]," homepage ": " http://www.xxx.com ",  "time":  "2014-12-30",  "license":  "MIT",  "authors": [{ "name": " Elvis Lim ", " email ": " elvis@xxx.com ",  "homepage":  "http://www.xxx.com",  "role": Span class= "hljs-string" > "Engineer"}]}        

If you are familiar with JSON format, then the above paragraph is self-evident. In fact, these key-value pairs are optional. In other words, you can never write. However, if you want to package the project into a public package to publish, then these still need to write, give your package name is never too much. Let's take a look at the meaning of these key-value pairs.


   
    "name":             "meta/silk",

Name, which represents the names of the packages. If you often mix on GitHub, the way this value is expressed must be familiar. As explained, the package name usually contains two parts and is separated by/. The front section of the diagonal bar, which represents the owner of the package. Most of the package authors now like to use GitHub's username as the value for this section. The back section of the diagonal bar represents the name of the package. Try to keep it simple and meaningful, easy to remember and spread. In most cases, many people will use GitHub's code base name, of course, in this case, the code to exist on GitHub is more meaningful.


   
    "description":      "another e-commerce website",

Introduction to the application, this section as concise as possible to introduce the next project, not lengthy. If you do have a lot of things to say, then you can write them in the readme.md file.


   
    "keywords":         ["silk", "online shop", "good"],

The value of a keyword is an array of strings that, when published as a common library, is useful as metadata information to facilitate the search and discovery of packages.


   
    "homepage":         "http://www.xxx.com ",

Homepage, you can put the address of any page you want to put.


   
    "license": "MIT",

If you decide to publish the package publicly, remember to choose a suitable license. When other programmers refer to the package, they check the license to make sure there are no legal issues.


   
     "authors":[{}]

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

So far, information about the package itself is described. As an e-commerce website, the ability to send emails, export orders to Excel tables is a basic requirement, and this is when you naturally think of using existing libraries to implement these functions. The easiest way to get these libraries is to search the libraries below, find the download address, download a zip package, and unzip it into the appropriate directory to bring in the appropriate files according to the document. With Composer, this process can be done more automatically and elegantly, which is Composer's dependency management.

Dependency Management

Add a new field to the Composer.json file: require. The value of this field is an object, which is also formed as a key-value pair. In the two dependent locations mentioned above, the way to write composer management is as follows:


    
     “require”: {"swiftmailer/swiftmailer": 5.3.*@dev,"phpoffice/phpexcel": "dev-master"}

Take Swiftmailer as an example, Swiftmailer/swiftmailer represents the package name, 5.3. @dev, is the version information. Together it means that the application we are going to develop depends on the Swiftmailer 5.3. Version. which

5.3.* says that you can use the 5.3.1 version, or you can use the 5.3.2 version, and composer will look for the latest version under version 5.3 when you get it. The version number supports a number of more general constraints, such as >=1.0, >=1.0, <2.0, and more specific information can be viewed: http://docs.phpcomposer.com/01-basic-usage.md#the- Require-key

@dev indicates that the development version can be obtained. Typically, a development version means a non-stable version, and there are likely bugs. A stability label can be applied to a specific dependency or to a global.

Role-specific dependencies: By default, composer will only get a stable version, if this example we do not add @dev constraints, and 5.3.* version is a development version, then in the acquisition of the composer will be an error, indicating that the revision does not meet the requirements. If you determine that the development version is not a problem, then you can add @dev, let composer get the development version.

Global stability Settings: By setting the value of Minimum-stability, you tell composer the global stability level of the package that is dependent on the currently developing project, and its values include: Dev, alpha, beta, RC, stable,stable are the default values.

At this point, two dependencies are added, we can run the next composer Package Update command to see the effect.


   
    composer install

After the successful run, the Vendor folder will be found in the root directory, containing the two package file code that we just listed.

Require-dev

Sometimes, we will find that some package dependencies will only be used in the development process, the formal release of the program does not need these packages, this time, you need to use another key, namely Require-dev. For example, if we want to use Codeception for unit testing, we can introduce a dependency package in this development environment through Require-dev:


    
     “require-dev”: {"codeception/codeception": "2.0.0 "}

After adding this dependency, run the command again to see the effect.


   
    composer install

Auto Load

Since then, composer has helped us to download the required library files, then the next thought is how to reference these library files. The simplest way is require or include, but this is not big enough, it takes time to go to the library file to see what files need to be introduced, trouble and error prone. Fortunately composer can help us solve this problem. That's autoload.

How do I call the Phpexcel library after running the composer install command? Very simple, as long as the introduction of the vendor directory of the autoload.php file is possible. In the root directory, you can build a index.php file to add content:

include “vendor/autoload.php”$excel = new PHPExcel();var_dump($excel);

Using a browser to access this page, you will find that the Phpexcel object has been successfully created, is not very convenient?

In fact, so far, we do not use the Composer.json file to add the AutoLoad field, then when to join it? That's when we want composer to help us automatically load our own defined classes. For example, we have written an order management class, named OrderManager, placed in the Lib directory in the ordermanager.php file. The contents are as follows:

class OrderManager{    public function test() { echo "hello"; }}

So how do you get composer to help us load this class automatically? Add the following content to the Composer.json:


    
     “autoload”:{    "files":["lib/OrderManager.php"]}

The value of the files key is an array, the array element is the path to the file, and the path is relative to the application's root directory. After adding the above content, run the command:


   
    composer dump-autoload

Let composer rebuild automatically loaded information, after completion, you can call the OrderManager class in the index.php.

The method introduced through the file, although intuitive, but very laborious, each file has to be introduced once, is not a good solution. Is there a better way? Try changing the value of the AutoLoad to:


   
     "classmap":["lib"]

Again this runs composer Dump-autoload, attempting to invoke, still able to successfully create the OrderManager class. In fact, classmap through the establishment of class-to-file correspondence, when the program needs OrderManager class, Compoer automatic loading class by looking for the OrderManager class is located in the file, and then change the file include. Therefore, this leads to a problem, that is, every addition of a new class, it is necessary to run a composer Dump-autoload to create the class to the file to the corresponding relationship, although the files method is a little better, but still very not pleasant ah! So, PSR-0 appeared. First understand what is PSR-0.

A set of PHP-related specifications developed by the FIG organization, referred to as PSR, where

PSR-0 Automatic loading
PSR-1 Basic Code specification
PSR-2 Code Style
PSR-3 Log Interface
PSR-4 Automatic loading

At the moment, at first glance, PSR-0 and PSR-4 are repeating, in fact, functionally repetitive. The difference is that the PSR-4 specification is clean, removing the content that is compatible with the previous version of PHP 5.3, with a bit of PSR-0 upgrade feel. Of course, PSR-4 is not to completely replace the PSR-0, but in the necessary time to add psr-0--of course, if you want to, PSR-4 can also replace PSR-0. PSR-4 can be used in conjunction with other automatic loading mechanisms, including PSR-0.

PSR-0 specifications of the specific contents see: Https://github.com/hfcorriez/fig-standards/blob/zh_CN/%E6%8E%A5%E5%8F%97/PSR-0.md
PSR-4 specifications of the specific contents see: Https://github.com/hfcorriez/fig-standards/blob/zh_CN/%E6%8E%A5%E5%8F%97/PSR-4-autoloader.md

In short, it is hoped that through a set of Conventions directory, file name, class name definition, to achieve fast through the class to find the file, and then included in the implementation of automatic loading.
The biggest difference between PSR-4 and PSR-0 is that the underscore (underscore) is defined differently. In PSR-4, the use of underscores in class names does not have any special meaning. PSR-0 Specifies that the underscore _ in the class name will be converted to a directory delimiter.

Both PSR-0 and PSR-4 require a namespace, so we need to make some minor changes to the OrderManager class, plus the namespace:

namespace SilkLib;class OrderManager{ public function test() { echo "hello"; } }

At the same time, the structure of the folder should be modified to: application root directory \lib\silklib\ordermanager.php

Then modify the AutoLoad section in Composer.json as follows:


    
     "autoload":{    "psr-0":{        "SilkLib":"lib/" }}

It should be noted here that Sliklib is a namespace, Lib is the directory name, their combination tells composer, file search is in: lib/silklib/directory, not in the Silklib/lib directory, this point to pay special attention, a bit around, easy to mistake.

If we change the namespace to Slik\lib, the corresponding directory structure should be changed to: The application root directory \lib\silk\lib\ordermanager.php,autoload part of the wording corresponding to change to:


    
     "autoload":{    "psr-0":{        "Silk\\lib":"lib/" }}

Note that the silk\lib is a double oblique rod. Well, let's try adding a class, and then don't run the composer Dump-autoload command to see if the new class can load. In the Lib directory, add a shipmanager.php file with the following content:

namespace Silk\lib;class ShipManager{ public function test() { echo 'hello ship class'; }}

Attempt to invoke in the index.php file:

$orderMgr = new Silk\lib\OrderManager();$orderMgr->test();$shipMgr = new Silk\lib\ShipManager();$shipMgr->test();

The success of the operation indicates that automatic loading using the PSR-0 specification is more convenient than classmap. Below try Psr-4 way, organize the directory structure, change to: Apply the root directory \lib\ordermanager.php, modify the namespace for silk, modify the AutoLoad section as:

"autoload":{    "psr-4":{        "Silk":"lib"    }}

Attempt to invoke, found error fatal error:uncaught exception ' invalidargumentexception ' with message ' a non-empty PSR-4 prefix must end with A namespace separator. Tip To add a delimiter, add it:


    
     "autoload":{    "psr-4":{        "Silk\\":"lib" }}

Composer Dump-autoload again, run the test, OK pass!

Master the Require and autoload parts, in fact, even if compoer, in detail, can be viewed composer documents to understand. Happy coding!

Original change to: http://my.oschina.net/u/248080/blog/359008

Thanks for the original

http://www.bkjia.com/PHPjc/1104656.html www.bkjia.com true http://www.bkjia.com/PHPjc/1104656.html techarticle "Go" composer get started, composer Getting started Java has maven, node. JS has NPM, ROR has gems, these language programmers are happy to use package management tools to accelerate development efficiency, phper are still replicating ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.