Bundle 是 Symfony 擴充功能的基本單位,類似其他框架的「模組/套件/外掛」,但地位更高:框架核心本身也是 Bundle(FrameworkBundle)。所有程式碼、設定、樣板、資源檔皆封裝於 Bundle 內,透過 AppKernel::registerBundles() 註冊啟用。
# 使用 MakerBundle 快速產生骨架 php bin/console make:bundle AcmeBlogBundle
或手動建立:
src/Acme/BlogBundle/ ├── AcmeBlogBundle.php # Bundle 類別(必要) ├── Controller/ ├── DependencyInjection/ # 擴充設定、編譯通過 ├── Resources/ │ ├── config/ │ │ ├── services.yaml # 服務定義 │ │ └── routes.yaml # 路由 │ ├── views/ # Twig 樣板 │ ├── translations/ # 翻譯檔 │ └── public/ # CSS/JS/圖片(需 assets:install) ├── Tests/ └── ...
| 項目 | 規範 | 範例 |
|---|---|---|
| Bundle 類別名 | Vendor + 類別 + Bundle,CamelCase | AcmeBlogBundle |
| 命名空間 | Vendor\Category\BundleName | Acme\BlogBundle |
| 目錄結構 | PSR-4 對應命名空間 | src/Acme/BlogBundle/ |
| 路由前綴 | bundle 別名小寫底線 | acme_blog_ |
| 服務 ID 前綴 | bundle 別名小寫底線 | acme_blog.service_name |
| 參數名稱前綴 | bundle 別名小寫底線 | acme_blog.email.from |
// src/Acme/BlogBundle/AcmeBlogBundle.php
namespace Acme\BlogBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AcmeBlogBundle extends Bundle
{
// 可選:自訂容器擴充、編譯通過
}
若需載入 services.yaml、處理設定、註冊編譯通過,建立 DependencyInjection/AcmeBlogExtension.php:
namespace Acme\BlogBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
class AcmeBlogExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yaml');
}
public function getAlias() { return 'acme_blog'; } // 設定檔鍵名
}
設定檔 config/packages/acme_blog.yaml 即可被自動處理。
# 將 Resources/public/ 連結/複製到 public/bundles/acmeblog/ php bin/console assets:install --symlink
樣板中引用:
{{ asset('bundles/acmeblog/css/style.css') }}
Resources/translations/messages.{locale}.xlf。acme_blog。應用層優先順序高於 Bundle 內部:
templates/bundles/AcmeBlogBundle/...(樣板)config/packages/acme_blog.yaml(設定)translations/AcmeBlogBundle.{locale}.xlf(翻譯)只需在對應路徑建立同名檔案即可覆寫,無需修改 vendor 目錄。
composer.json 含 name、type: symfony-bundle、autoload.psr-4、require 相依套件。README.md、LICENSE、CHANGELOG.md 完整。private: true(預設),僅公開必要入口。form_theme。phpunit 可獨立執行。遵循標準結構與命名慣例,能讓 Bundle 輕鬆被社群採用、整合至專案、並長期維護。核心原則:高內聚、低耦合、可配置、可覆寫、可測試。