> Symfony中文手册 > 如何安装第三方Bundle

如何安装第三方Bundle

大多数Bundle都提供自己的安装说明。然而,安装bundle的基本步骤都是相同的:

  • A) 添加Composer依赖

  • B) 启用Bundle

  • C) 配置Bundle

A) 添加Composer依赖 ¶

Composer管理依赖,所以如果Composer对于你来说是一个新的概念,可以在他们的文档中学习一些基本知识。添加Composer涉及两个步骤:

1) 在Packagist找出Bundle的名称 ¶

Bundle(如,FOSUserBundle)的README(自述文件)通常会告诉你它的名字(如,friendsofsymfony/user-bundle)。 如果它们没有,你可以在Packagist.org网站中查询这个bundle。

如何寻找Bundle?尝试在 KnpBundles.com 搜索:这些都是非官方的Symfony Bundles归档。

2) 通过Composer安装Bundle ¶

现在你知道了包的名称,你可以通过Composer来安装它:

1
$ composer require friendsofsymfony/user-bundle

这将为您的项目选择最好的版本,把它添加到composer.json并下载它的代码到vendor/目录。如果你需要一个指定的版本,可以它作为composer require命令的第二个参数:

1
$ composer require friendsofsymfony/user-bundle "~2.0"

B) 启用Bundle ¶

此时,Bundle已经被安装到了symfony项目中(在vendor/friendsofsymfony/中)并且自动识别出了它的类。现在你需要做的唯一一件事就是在 AppKernel 中注册 bundle:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// app/AppKernel.PHP
 
// ...
class AppKernel extends Kernel
{
    // ...
 
    public function registerBundles()
    {
        $bundles = array(
            // ...
            new FOS\UserBundle\FOSUserBundle(),
        );
 
        // ...
    }
}

在一些罕见的情况下,你可能想要一个Bundle只在开发环境中启用。例如,DoctrineFixturesBundle 有助于假数据的加载 - 这些事你可能只想在开发环境中去做。只在devtest环境中加载这个bundle,就需要以这种方式注册Bundle:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// app/AppKernel.php
 
// ...
class AppKernel extends Kernel
{
    // ...
 
    public function registerBundles()
    {
        $bundles = array(
            // ...
        );
 
        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle();
        }
 
        // ...
    }
}

C)配置Bundle ¶

对于Bundle来说需要一些额外的设置或者在app/config/config.yml中配置是很常见的事情。Bundle的文档会告诉你他们如何设置,但是你也可以通过 config:dump-reference 命令来获取一些 bundle 的设置指导:

1
$ bin/console config:dump-reference AsseticBundle

取代 bundle 的全名,你也可以把Bundle配置的根名称作为短名称传入:

1
$ bin/console config:dump-reference assetic

输出结果如下:

1
2
3
4
5
6
7
8
9
10
11
assetic:
    debug:                '%kernel.debug%'
    use_controller:
        enabled:              '%kernel.debug%'
        profiler:             false
    read_from:            '%kernel.root_dir%/../web'
    write_to:             '%assetic.read_from%'
    java:                 /usr/bin/java
    node:                 /usr/local/bin/node
    node_paths:           []
    # ...

其他设置 ¶

此时,阅读你这个新 bundle 的 README 文件来看看下一步要做什么。祝你玩的开心!