跳到内容

Bundle 系统

编辑此页

警告

在 Symfony 4.0 之前的版本中,建议使用 bundle 来组织你自己的应用程序代码。现在不再推荐这样做,bundle 应该只用于在多个应用程序之间共享代码和功能。

Bundle 类似于其他软件中的插件,但更出色。Symfony 框架的核心功能是通过 bundle 实现的 (FrameworkBundle, SecurityBundle, DebugBundle 等)。它们也用于通过 第三方 bundle 在你的应用程序中添加新功能。

在你的应用程序中使用的 Bundle 必须在 config/bundles.php 文件中根据环境启用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// config/bundles.php
return [
    // 'all' means that the bundle is enabled for any Symfony environment
    Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
    // ...

    // this bundle is enabled only in 'dev'
    Symfony\Bundle\DebugBundle\DebugBundle::class => ['dev' => true],
    // ...

    // this bundle is enabled only in 'dev' and 'test', so you can't use it in 'prod'
    Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => true],
    // ...
];

提示

在使用 Symfony Flex 的默认 Symfony 应用程序中,bundle 会在你安装/移除它们时自动启用/禁用,因此你无需查看或编辑此 bundles.php 文件。

创建 Bundle

本节创建一个新的 bundle 并启用它,以展示只需几个步骤即可完成。新的 bundle 被称为 AcmeBlogBundle,其中 Acme 部分是一个示例名称,应替换为代表你或你的组织的“供应商”名称(例如,对于名为 Abc 的公司,可以使用 AbcBlogBundle)。

首先创建一个名为 AcmeBlogBundle 的新类

1
2
3
4
5
6
7
8
// src/AcmeBlogBundle.php
namespace Acme\BlogBundle;

use Symfony\Component\HttpKernel\Bundle\AbstractBundle;

class AcmeBlogBundle extends AbstractBundle
{
}

警告

如果你的 bundle 必须与以前的 Symfony 版本兼容,你必须从 Bundle 继承。

提示

名称 AcmeBlogBundle 遵循标准的 Bundle 命名约定。你也可以选择将 bundle 的名称缩短为简单的 BlogBundle,通过将此类命名为 BlogBundle (并将文件命名为 BlogBundle.php)。

这个空类是你创建新 bundle 唯一需要的部分。虽然通常为空,但此类功能强大,可用于自定义 bundle 的行为。现在你已经创建了 bundle,启用它

1
2
3
4
5
// config/bundles.php
return [
    // ...
    Acme\BlogBundle\AcmeBlogBundle::class => ['all' => true],
];

虽然它目前什么都不做,但 AcmeBlogBundle 现在已准备好使用。

Bundle 目录结构

bundle 的目录结构旨在帮助保持所有 Symfony bundle 之间的代码一致性。它遵循一组约定,但也具有灵活性,可以根据需要进行调整

assets/
包含 Web 资源源,如 JavaScript 和 TypeScript 文件、CSS 和 Sass 文件,以及与 bundle 相关的其他资源,这些资源不在 public/ 中(例如 Stimulus 控制器)。
config/
存放配置,包括路由配置(例如 routes.php)。
public/
包含 Web 资源(图像、编译后的 CSS 和 JavaScript 文件等),并通过 assets:install 控制台命令复制或符号链接到项目 public/ 目录中。
src/
包含与 bundle 逻辑相关的所有 PHP 类(例如 Controller/CategoryController.php)。
templates/
保存按控制器名称组织的模板(例如 category/show.html.twig)。
tests/
保存 bundle 的所有测试。
translations/
保存按域和区域设置组织的翻译(例如 AcmeBlogBundle.zh_CN.xlf)。

警告

推荐的 bundle 结构在 Symfony 5 中发生了更改,请阅读Symfony 4.4 bundle 文档,了解旧结构的信息。

当使用新的 AbstractBundle 类时,bundle 默认使用新结构。覆盖 Bundle::getPath() 方法可以更改为旧结构

1
2
3
4
5
6
7
class AcmeBlogBundle extends AbstractBundle
{
    public function getPath(): string
    {
        return __DIR__;
    }
}

提示

建议使用 PSR-4 自动加载标准:使用命名空间作为键,bundle 主类的位置(相对于 composer.json)作为值。由于主类位于 bundle 的 src/ 目录中

1
2
3
4
5
6
7
8
9
10
11
12
{
    "autoload": {
        "psr-4": {
            "Acme\\BlogBundle\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Acme\\BlogBundle\\Tests\\": "tests/"
        }
    }
}
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可获得许可。
目录
    版本