composer.json 綱要#

本章會解釋在 composer.json 中所有的可用欄位。

JSON 綱要#

我們有一個 JSON 綱要,它紀錄了格式而且也可以被用來驗證你的 composer.json。事實上,它被 validate 命令使用。你可以在這裡找到它:https://getcomposer.org/schema.json

Root 套件#

The root package is the package defined by the composer.json at the root of your project. 它是定義你專案需求的主要 composer.json

某些欄位只應用在 root 套件的情境。其中一個例子是 config 欄位。只有 root 套件可以定義配置。 依賴套件的配置會被忽略。這使得 config 欄位 root-only

注意: A package can be the root package or not, depending on the context. For example, if your project depends on the monolog library, your project is the root package. However, if you clone monolog from GitHub in order to fix a bug in it, then monolog is the root package.

屬性#

name#

套件的名稱。它包括 vendor 和專案名稱,用 / 分隔。例如:

The name can contain any character, including white spaces, and it's case insensitive (foo/bar and Foo/Bar are considered the same package). In order to simplify its installation, it's recommended to define a short and lowercase name that doesn't include non-alphanumeric characters or white spaces.

對已發表套件(函式庫)是必要的。

description#

套件的簡短描述。通常這只有一行的長度。

對已發表套件(函式庫)是必要。

version#

套件的版本。在大多數情況下,這不是必要的,並且應該被忽略 (見下文)。

This must follow the format of X.Y.Z or vX.Y.Z with an optional suffix of -dev, -patch-p), -alpha-a), -beta-b) or -RC. The patch, alpha, beta and RC suffixes can also be followed by a number.

範例:

Optional if the package repository can infer the version from somewhere, such as the VCS tag name in the VCS repository. In that case it is also recommended to omit it.

注意: Packagist uses VCS repositories, so the statement above is very much true for Packagist as well. Specifying the version yourself will most likely end up creating problems at some point due to human error.

type#

套件類型。預設是 library

Package types are used for custom installation logic. If you have a package that needs some special logic, you can define a custom type. This could be a symfony-bundle, a wordpress-plugin or a typo3-cms-extension. These types will all be specific to certain projects, and they will need to provide an installer capable of installing packages of that type.

開箱即用,Composer 支援四種類型:

Only use a custom type if you need custom logic during installation. It is recommended to omit this field and have it just default to library.

keywords#

一個套件關聯的關鍵字陣列。 這些可以被用於搜尋和篩選。

範例:

選擇性。

homepage#

指向專案網站的 URL。

選擇性。

time#

該版本的發行日期。

必須是 YYYY-MM-DDYYYY-MM-DD HH:MM:SS 的格式。

選擇性。

license#

套件的授權許可。這可以是一個字串或一個字串的陣列。

最常見的授權許可建議的寫法是(按字母順序排列):

Optional, but it is highly recommended to supply this. More identifiers are listed at the SPDX Open Source License Registry.

For closed-source software, you may use "proprietary" as the license identifier.

一個範例:

{
    "license": "MIT"
}

For a package, when there is a choice between licenses ("disjunctive license"), multiple can be specified as array.

An Example for disjunctive licenses:

{
    "license": [
       "LGPL-2.1",
       "GPL-3.0+"
    ]
}

Alternatively they can be separated with "or" and enclosed in parenthesis;

{
    "license": "(LGPL-2.1 or GPL-3.0+)"
}

Similarly when multiple licenses need to be applied ("conjunctive license"), they should be separated with "and" and enclosed in parenthesis.

authors#

套件的作者。這是一個物件的陣列。

每個作者物件可以有以下屬性:

一個範例:

{
    "authors": [
        {
            "name": "Nils Adermann",
            "email": "naderman@naderman.de",
            "homepage": "http://www.naderman.de",
            "role": "Developer"
        },
        {
            "name": "Jordi Boggiano",
            "email": "j.boggiano@seld.be",
            "homepage": "http://seld.be",
            "role": "Developer"
        }
    ]
}

選擇性,但強烈推薦。

support#

來取得專案支援的各種資訊。

支援包括以下的資訊:

一個範例:

{
    "support": {
        "email": "support@example.org",
        "irc": "irc://irc.freenode.org/composer"
    }
}

選擇性。

All of the following take an object which maps package names to versions of the package via version constraints. Read more about versions here.

範例:

{
    "require": {
        "monolog/monolog": "1.0.*"
    }
}

所有連結都是選擇性欄位。

requirerequire-dev 額外支援 stability 旗標(僅適用 root)。 These allow you to further restrict or expand the stability of a package beyond the scope of the minimum-stability setting. You can apply them to a constraint, or just apply them to an empty constraint if you want to allow unstable packages of a dependency for example.

範例:

{
    "require": {
        "monolog/monolog": "1.0.*@beta",
        "acme/foo": "@dev"
    }
}

If one of your dependencies has a dependency on an unstable package you need to explicitly require it as well, along with its sufficient stability flag.

範例:

{
    "require": {
        "doctrine/doctrine-fixtures-bundle": "dev-master",
        "doctrine/data-fixtures": "@dev"
    }
}

require and require-dev additionally support explicit references (i.e. commit) for dev versions to make sure they are locked to a given state, even when you run update. These only work if you explicitly require a dev version and append the reference with #<ref>.

範例:

{
    "require": {
        "monolog/monolog": "dev-master#2eb0c0978d290a1c45346a1955188929cb4e5db7",
        "acme/foo": "1.0.x-dev#abc123"
    }
}

注意: This feature has severe technical limitations, as the composer.json metadata will still be read from the branch name you specify before the hash. You should therefore only use this as a temporary solution during development to remediate transient issues, until you can switch to tagged releases. The Composer team does not actively support this feature and will not accept bug reports related to it.

It is also possible to inline-alias a package constraint so that it matches a constraint that it otherwise would not. 更多資訊, 參閱別名主題

require and require-dev also support references to specific PHP versions and PHP extensions your project needs to run successfully.

範例:

{
    "require" : {
        "php" : "^5.5 || ^7.0",
        "ext-mbstring": "*"
    }
}

Note: It is important to list PHP extensions your project requires. Not all PHP installations are created equal: some may miss extensions you may consider as standard (such as ext-mysqli which is not installed by default in Fedora/CentOS minimal installation systems). Failure to list required PHP extensions may lead to a bad user experience: Composer will install your package without any errors but it will then fail at run-time. The composer show --platform command lists all PHP extensions available on your system. You may use it to help you compile the list of extensions you use and require. Alternatively you may use third party tools to analyze your project for the list of extensions used.

require#

Lists packages required by this package. The package will not be installed unless those requirements can be met.

require-dev僅適用 root#

Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both install or update support the --no-dev option that prevents dev dependencies from being installed.

conflict#

Lists packages that conflict with this version of this package. They will not be allowed to be installed together with your package.

Note that when specifying ranges like <1.0 >=1.1 in a conflict link, this will state a conflict with all versions that are less than 1.0 and equal or newer than 1.1 at the same time, which is probably not what you want. You probably want to go for <1.0 || >=1.1 in this case.

replace#

Lists packages that are replaced by this package. This allows you to fork a package, publish it under a different name with its own version numbers, while packages requiring the original package continue to work with your fork because it replaces the original package.

This is also useful for packages that contain sub-packages, for example the main symfony/symfony package contains all the Symfony Components which are also available as individual packages. If you require the main package it will automatically fulfill any requirement of one of the individual components, since it replaces them.

Caution is advised when using replace for the sub-package purpose explained above. You should then typically only replace using self.version as a version constraint, to make sure the main package only replaces the sub-packages of that exact version, and not any other version, which would be incorrect.

provide#

List of other packages that are provided by this package. This is mostly useful for common interfaces. A package could depend on some virtual logger package, any library that implements this logger interface would simply list it in provide.

suggest#

Suggested packages that can enhance or work well with this package. These are just informational and are displayed after the package is installed, to give your users a hint that they could add more packages, even though they are not strictly required.

The format is like package links above, except that the values are free text and not version constraints.

範例:

{
    "suggest": {
        "monolog/monolog": "Allows more advanced logging of the application flow",
        "ext-xml": "Needed to support XML format in class Foo"
    }
}

autoload#

Autoload mapping for a PHP autoloader.

PSR-4 and PSR-0 autoloading, classmap generation and files includes are supported.

PSR-4 is the recommended way since it offers greater ease of use (no need to regenerate the autoloader when you add classes).

PSR-4#

psr-4 鍵底下,你定義一個從命名空間到路徑的對映,相對於套件 root。When autoloading a class like Foo\\Bar\\Baz a namespace prefix Foo\\ pointing to a directory src/ means that the autoloader will look for file named src/Bar/Baz.php and include it if present. Note that as opposed to the older PSR-0 style, the prefix (Foo\\) is not present in the file path

Namespace prefixes must end in \\ to avoid conflicts between similar prefixes For example Foo would match classes in the FooBar namespace so the trailing backslashes solve the problem: Foo\\ and FooBar\\ are distinct.

The PSR-4 references are all combined, during install/update, into a single key => value array which may be found in the generated file vendor/composer/autoload_psr4.php.

範例:

{
    "autoload": {
        "psr-4": {
            "Monolog\\": "src/",
            "Vendor\\Namespace\\": ""
        }
    }
}

如果你需要在多個目錄中搜尋相同前綴, 你可以像這樣指定他們為一個陣列:

{
    "autoload": {
        "psr-4": { "Monolog\\": ["src/", "lib/"] }
    }
}

如果你想要有一個任何命名空間可以用的備用目錄, 你可以像這樣使用一個空前綴:

{
    "autoload": {
        "psr-4": { "": "src/" }
    }
}

PSR-0#

psr-0 鍵底下,你定義一個從命名空間到路徑的對映,相對於套件 root。Note that this also supports the PEAR-style non-namespaced convention.

Please note namespace declarations should end in \\ to make sure the autoloader responds exactly. For example Foo would match in FooBar so the trailing backslashes solve the problem: Foo\\ and FooBar\\ are distinct.

The PSR-0 references are all combined, during install/update, into a single key => value array which may be found in the generated file vendor/composer/autoload_namespaces.php.

範例:

{
    "autoload": {
        "psr-0": {
            "Monolog\\": "src/",
            "Vendor\\Namespace\\": "src/",
            "Vendor_Namespace_": "src/"
        }
    }
}

如果你需要在多個目錄中搜尋一個相同前綴, 你可以像這樣指定他們為一個陣列:

{
    "autoload": {
        "psr-0": { "Monolog\\": ["src/", "lib/"] }
    }
}

The PSR-0 style is not limited to namespace declarations only but may be specified right down to the class level. This can be useful for libraries with only one class in the global namespace. If the php source file is also located in the root of the package, 例如,它可能像這樣被宣告:

{
    "autoload": {
        "psr-0": { "UniqueGlobalClass": "" }
    }
}

如果你想要有一個任何命名空間可以用的備用目錄, 你可以像這樣使用一個空前綴:

{
    "autoload": {
        "psr-0": { "": "src/" }
    }
}

Classmap#

The classmap references are all combined, during install/update, into a single key => value array which may be found in the generated file vendor/composer/autoload_classmap.php. This map is built by scanning for classes in all .php and .inc files in the given directories/files.

You can use the classmap generation support to define autoloading for all libraries that do not follow PSR-0/4. To configure this you specify all directories or files to search for classes.

範例:

{
    "autoload": {
        "classmap": ["src/", "lib/", "Something.php"]
    }
}

Files#

If you want to require certain files explicitly on every request then you can use the 'files' autoloading mechanism. This is useful if your package includes PHP functions that cannot be autoloaded by PHP.

範例:

{
    "autoload": {
        "files": ["src/MyLibrary/functions.php"]
    }
}

從 classmaps 排除檔案#

If you want to exclude some files or folders from the classmap you can use the 'exclude-from-classmap' property. This might be useful to exclude test classes in your live environment, for example, as those will be skipped from the classmap even when building an optimized autoloader.

The classmap generator will ignore all files in the paths configured here. The paths are absolute from the package root directory (i.e. composer.json location), and support * to match anything but a slash, and ** to match anything. ** is implicitly added to the end of the paths.

範例:

{
    "autoload": {
        "exclude-from-classmap": ["/Tests/", "/test/", "/tests/"]
    }
}

Optimizing the autoloader#

The autoloader can have quite a substantial impact on your request time (50-100ms per request in large frameworks using a lot of classes). See the article about optimizing the autoloader for more details on how to reduce this impact.

autoload-dev僅適用 root#

本段落允許為開發用途定義自動載入規則。

Classes needed to run the test suite should not be included in the main autoload rules to avoid polluting the autoloader in production and when other people use your package as a dependency.

Therefore, it is a good idea to rely on a dedicated path for your unit tests and to add it within the autoload-dev section.

範例:

{
    "autoload": {
        "psr-4": { "MyLibrary\\": "src/" }
    },
    "autoload-dev": {
        "psr-4": { "MyLibrary\\Tests\\": "tests/" }
    }
}

include-path#

棄用:This is only present to support legacy projects, and all new code should preferably use autoloading. As such it is a deprecated practice, but the feature itself will not likely disappear from Composer.

A list of paths which should get appended to PHP's include_path.

範例:

{
    "include-path": ["lib/"]
}

選擇性。

target-dir#

棄用:This is only present to support legacy PSR-0 style autoloadin and all new code should preferably use PSR-4 without target-dir and projects using PSR-0 with PHP namespaces are encouraged to migrate to PSR-4 instead.

定義安裝目標。

In case the package root is below the namespace declaration you cannot autoload properly. target-dir solves this problem.

An example is Symfony. There are individual packages for the components. The Yaml component is under Symfony\Component\Yaml. The package root is that Yaml directory. To make autoloading possible, we need to make sure that it is not installed into vendor/symfony/yaml, but instead into vendor/symfony/yaml/Symfony/Component/Yaml, so that the autoloader can load it from vendor/symfony/yaml.

To do that, autoload and target-dir are defined as follows:

{
    "autoload": {
        "psr-0": { "Symfony\\Component\\Yaml\\": "" }
    },
    "target-dir": "Symfony/Component/Yaml"
}

選擇性。

minimum-stability僅適用 root#

This defines the default behavior for filtering packages by stability. 這預設為 stable。so if you rely on a dev package, you should specify it in your file to avoid surprises.

All versions of each package are checked for stability, and those that are less stable than the minimum-stability setting will be ignored when resolving your project dependencies. (Note that you can also specify stability requirements on a per-package basis using stability flags in the version constraints that you specify in a require block (see package links for more details).

可用的選項(依穩定性順序)有 devalphabetaRCstable

prefer-stable僅適用 root#

When this is enabled, Composer will prefer more stable packages over unstable ones when finding compatible stable packages is possible. If you require a dev version or only alphas are available for a package, those will still be selected granted that the minimum-stability allows for it.

使用 "prefer-stable": true 來啟用。

repositories僅適用 root#

自訂套件儲存庫來使用。

預設情況下,Composer 只使用 packagist 儲存庫。 透過指定儲存庫,你可以從其他地方取得套件。

儲存庫不會遞迴地解析。你只能添加他們到你主要的 composer.json。依賴套件中 composer.json 的儲存庫宣告會被忽略。

支援以下儲存庫類型:

更多關於這些的任何資訊,詳見 儲存庫

範例:

{
    "repositories": [
        {
            "type": "composer",
            "url": "http://packages.example.com"
        },
        {
            "type": "composer",
            "url": "https://packages.example.com",
            "options": {
                "ssl": {
                    "verify_peer": "true"
                }
            }
        },
        {
            "type": "vcs",
            "url": "https://github.com/Seldaek/monolog"
        },
        {
            "type": "pear",
            "url": "https://pear2.php.net"
        },
        {
            "type": "package",
            "package": {
                "name": "smarty/smarty",
                "version": "3.1.7",
                "dist": {
                    "url": "http://www.smarty.net/files/Smarty-3.1.7.zip",
                    "type": "zip"
                },
                "source": {
                    "url": "https://smarty-php.googlecode.com/svn/",
                    "type": "svn",
                    "reference": "tags/Smarty_3_1_7/distribution/"
                }
            }
        }
    ]
}

注意: Order is significant here. When looking for a package, Composer will look from the first to the last repository, and pick the first match. By default Packagist is added last which means that custom repositories can override packages from it.

Using JSON object notation is also possible. However, JSON key/value pairs are to be considered unordered so consistent behaviour cannot be guaranteed.

{
    "repositories": {
         "foo": {
             "type": "composer",
             "url": "http://packages.foo.com"
         }
    }
}

config 僅適用 root#

A set of configuration options. It is only used for projects. See Config for a description of each individual option.

scripts僅適用 root#

Composer allows you to hook into various parts of the installation process through the use of scripts.

事件細節及範例,詳見 Scripts

extra#

Arbitrary extra data for consumption by scripts.

This can be virtually anything. To access it from within a script event handler, 你可以這樣做:

$extra = $event->getComposer()->getPackage()->getExtra();

選擇性。

bin#

一組應該被視為二進制文件的檔案,並符號連結到 bin-dir (來自 config)。

更多細節,詳見 Vendor 二進制文件

選擇性。

archive#

一組用於建立套件封存的選項。

支援以下選項:

範例:

{
    "archive": {
        "exclude": ["/foo/bar", "baz", "/*.test", "!/foo/bar/baz"]
    }
}

該範例會包含 /dir/foo/bar/file/foo/bar/baz/file.php/foo/my.test 但會排除 /foo/bar/any/foo/baz/my.test

選擇性。

non-feature-branches#

A list of regex patterns of branch names that are non-numeric (e.g. "latest" or something), that will NOT be handled as feature branches. This is an array of strings.

If you have non-numeric branch names, for example like "latest", "current", "latest-stable" or something, that do not look like a version number, then Composer handles such branches as feature branches. This means it searches for parent branches, that look like a version or ends at special branches (like master) and the root package version number becomes the version of the parent branch or at least master or something.

To handle non-numeric named branches as versions instead of searching for a parent branch with a valid version or special branch name like master, you can set patterns for branch names, that should be handled as dev version branches.

This is really helpful when you have dependencies using "self.version", so that not dev-master, but the same branch is installed (in the example: latest-testing).

An example:

If you have a testing branch, that is heavily maintained during a testing phase and is deployed to your staging environment, normally "composer show -s" will give you versions : * dev-master.

If you configure latest-.* as a pattern for non-feature-branches like this:

{
    "non-feature-branches": ["latest-.*"]
}

Then "composer show -s" will give you versions : * dev-latest-testing.

Optional.

feature-branches#

If your feature branch names are other than the default names:

You can use this setting to declare the list of branch names which should be considered feature branches in your package. For example, if you do not use develop but rather use a name like development and have no trunk or default branches, you can change this setting to:

{
    "feature-branches": ["master", "development"]
}

And Composer will consider those two branches (plus any numeric branches) as your only feature branches. This allows Composer to recognise when you create a new branch based on such a non-standard named feature branch, that your new branch is based on that "version".

In practice this allows you to have my/package:dev-oddname in your dependency section and still have my/package:dev-branchofoddname be recognised as compatible. Without overriding this configuration option, Composer would instead demand that you explicitly install my/package:dev-oddname or change the dependency to the explicit name my/package:dev-branchofoddname.

Particularly useful when combined with local repositories of type path where Composer will read the checked-out branch name to determine the version. Without this setting, if you used non-standard names, Composer would reject creating a symlink to the path and will instead force git clone. With the setting, symlink creation is allowed when your local branches are based on such non-standard named feature branches.

Note that this is only the case when your branch names are other than the above mentioned four default branch names. When you use default names you never need to declare this list - Composer will then detect your feature branches based on the default set of names.

Optional.

命令列介面 | 儲存庫

發現錯字?在這個文件中有些錯誤?只要 fork 並編輯 它!