Shopware 6 開發
核心架構
Shopware 6 是一個 PHP/Symfony 平台。在產生程式碼之前,請先釐清要針對哪一層進行開發:
| 層級 | 技術 | 位置 |
|---|---|---|
| Core / PHP | PHP 8.2+, Symfony 7.4 (SW 6.7) / Symfony 7.0 (SW 6.6) | src/ — 服務, DAL, 事件 |
| Storefront | Twig 3, SCSS, Vanilla JS, Vite dev server (6.7.11+) | src/Resources/views/storefront/ |
| Admin | Vue 3, Pinia, Meteor 元件 (mt-*), Vite build | src/Resources/app/administration/ |
| App System | manifest.xml (schema 3.0 in 6.7), App Scripts | 外部伺服器或 Twig 腳本 (無需 PHP) |
Plugin vs App System: 對於需要直接存取 PHP/DB 的自託管安裝,請使用 Plugin。對於 SaaS/多租戶或目標為 Shopware 商店的應用,請使用 App System。
這是哪個版本?
在產生程式碼之前,請詢問或推斷目標版本。目前主線是 6.7.13.x;6.8 計畫於 2027 年推出。6.7 改動了許多外掛程式 API,因此在 6.6 上正確的程式碼在 6.7 上通常是錯誤的:
| 主題 | SW 6.6 | SW 6.7 |
|---|---|---|
| 付款處理器 | Synchronous/AsynchronousPaymentHandlerInterface | AbstractPaymentHandler |
| Administration 元件 | sw-button, sw-card, sw-text-field | mt-button, mt-card, mt-text-field |
| Administration 狀態管理 | Vuex Shopware.State (已棄用) | Pinia Shopware.Store 僅限 |
| Administration 建置工具 | Webpack | Vite |
EntityExtension | getDefinitionClass() | 加上抽象 getEntityName() |
| 外掛程式自訂實體 | entities.xml | 已移除,請使用 EntityDefinition |
IdsCollection | Shopware\Core\Framework\Test\ | Shopware\Core\Test\Stub\Framework\ |
完整列表請參考 references/migration-6.7.md。當版本未知時,請以 6.7 為目標,並註明與 6.6 的差異。
Plugin 結構
PluginName/
├── composer.json
├── src/
│ ├── PluginName.php # 啟動類別
│ ├── Resources/
│ │ ├── config/
│ │ │ └── services.xml # Symfony DI 容器
│ │ ├── views/
│ │ │ └── storefront/ # Twig 樣板覆寫
│ │ └── app/
│ │ └── administration/ # Vue.js 管理後台擴充
│ └── Migration/ # 資料庫遷移
└── tests/
Plugin 啟動
<?php declare(strict_types=1);
namespace VendorName\PluginName;
use Shopware\Core\Framework\Plugin;
class PluginName extends Plugin {}
僅在需要生命週期動作(例如建立付款方式、卸載時刪除資料表)時,才擴充 install()、activate()、deactivate()、uninstall() 方法。
五大核心工作流程
1. 註冊服務 (DI)
<!-- services.xml -->
<service id="VendorName\PluginName\Service\MyService">
<argument type="service" id="product.repository"/>
</service>
常見標籤:kernel.event_subscriber, twig.extension, console.command, messenger.message_handler, shopware.entity.definition, shopware.entity.extension, shopware.rule.definition, shopware.payment.method.sync, shopware.payment.method.async, shopware.cms.element。
2. 監聽事件 (Subscriber)
class ProductSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return ['product.written' => 'onProductWritten'];
}
public function onProductWritten(EntityWrittenEvent $event): void
{
foreach ($event->getWriteResults() as $result) {
$id = $result->getPrimaryKey();
}
}
}
3. DAL 讀寫
// 讀取
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('active', true));
$criteria->addAssociation('manufacturer');
$result = $this->productRepository->search($criteria, $context);
// 寫入
$this->productRepository->upsert([
['id' => $id, 'name' => '新名稱'],
], $context);
4. 覆寫 Storefront 樣板
{# 鏡像 views/storefront/ 下的原始路徑 #}
{% sw_extends '@Storefront/storefront/page/product-detail/index.html.twig' %}
{% block page_product_detail_content %}
<div class="my-banner">自訂內容</div>
{{ parent() }}
{% endblock %}
5. 裝飾服務
<service id="VendorName\PluginName\Decorator\MyDecorator"
decorates="original.service.id">
<argument type="service"
id="VendorName\PluginName\Decorator\MyDecorator.inner"/>
</service>
Karpathy 原則 — 編碼前先釐清
在產生程式碼之前,請先陳述這些假設:
- 版本? SW 6.5 vs 6.6 (API 和 Vue 元件存在差異)
- Plugin 或 App System? Plugin = PHP 伺服器;App = manifest.xml + 外部/無伺服器
- 層級? PHP/Core, Storefront, Admin, 或無頭/Store API
- 讀取或寫入? Repository
search()vsupsert()/create()/update() - 實體或擴充? 新資料表 vs 擴展現有實體
只撰寫解決問題所需的最小化程式碼。Shopware 的 DI 與事件系統能處理大部分複雜性。
DAL 快速參考
// Criteria
$criteria->addFilter(new EqualsFilter('active', true));
$criteria->addFilter(new ContainsFilter('name', 'shirt'));
$criteria->addFilter(new RangeFilter('price', [RangeFilter::GTE => 10]));
$criteria->addAssociation('manufacturer');
$criteria->addSorting(new FieldSorting('name', FieldSorting::ASCENDING));
$criteria->setLimit(25)->setOffset(0);
// Context
$context = Context::createDefaultContext(); // 系統
// 或從路由/事件注入 SalesChannelContext
// 僅取得 ID (較快,無需 hydrate)
$ids = $this->repo->searchIds($criteria, $context)->getIds();
Administration Vue.js 快速參考
// 註冊模組
Shopware.Module.register('my-module', {
type: 'plugin',
routes: { index: { component: 'my-module-index', path: 'index' } },
navigation: [{ label: 'my-module.title', path: 'my.module.index', icon: 'default-shopping-paper-bag' }],
});
// 覆寫現有元件
Shopware.Component.override('sw-product-detail', {
methods: {
async saveProduct() {
await this.$super('saveProduct'); // 呼叫原始方法
},
},
});
CLI 指令
bin/console plugin:install --activate PluginName
bin/console database:migrate --all PluginName
bin/console cache:clear
bin/console plugin:refresh
bin/build-administration.sh
bin/build-storefront.sh
bin/console theme:compile
php vendor/bin/phpunit --testsuite=unit
vendor/bin/phpstan analyse src --level=8
其他資源
參考檔案
在處理特定領域時,請載入這些檔案:
- references/dal.md — DAL:EntityDefinition, Criteria, Aggregations, 自訂欄位, Entity Extensions (擴充核心實體)
- references/admin.md — Administration:Vue 模組, 元件, 覆寫, 命名慣例, ACL 權限, 篩選/內聯編輯, 搜尋設定
- references/storefront.md — Storefront:Twig 繼承, SCSS/主題變數, JavaScript 外掛程式, 控制器
- references/themes.md — 主題:theme.json (設定欄位, 顏色, 字型, 媒體), SCSS Bootstrap 覆寫, 主題繼承, ThemeInterface, CLI 指令
- references/cart.md — 購物車:CartDataCollector, CartProcessor, CartValidator + 自訂錯誤, 折扣明細項目, 價格操作, Tax Provider
- references/seo-mail.md — SEO:SeoUrlRoute, 網站地圖 URL provider;郵件:自訂郵件樣板 (遷移 + 傳送);文件 (自訂 PDF 類型);訂單狀態機 (轉換, 事件)
- references/plugin-structure.md — 完整 plugin 架構:services.xml, 生命週期鉤子, composer.json, 控制台指令, 排程任務
- references/api.md — Admin API & Store API:CRUD, 批次, 篩選;context token 生命週期, 購物車/結帳/帳戶 Store API, TypeScript 客戶端模式
- references/testing.md — PHPUnit 單元/整合測試, StaticEntityRepository, ProductBuilder, Jest, Cypress, assertSame vs assertEquals
- references/app-system.md — App System:manifest.xml, webhook HMAC 驗證, 註冊交握, App Scripts (基於 Twig, 無伺服器)
- references/security.md — 安全性:路由範圍, CSRF 保護, 輸入驗證, 按客戶授權, SQL 注入防範
- references/integrations.md — 整合:Payment Handler (
AbstractPaymentHandler), 運費 (購物車處理器, 非計算器標籤), CMS Elements, Rule Builder 條件, Flow Builder 事件 - references/performance.md — 效能:HTTP Cache (標籤, 失效), Message Queue (非同步處理), Elasticsearch/OpenSearch, 物件快取
- references/devops.md — DevOps:結構化日誌, PHPStan, php-cs-fixer, CI/CD, 部署, 除錯, 媒體處理, 升級安全
- references/migration-6.7.md — 6.6 到 6.7 遷移:跨 Core/DAL, Admin, Storefront, 快取, API, 託管的重大變更,以及 6.7.x 新增的功能 (Vite dev server, Twig UX 元件, MCP server)
- references/advanced.md — 進階:PHP Attributes 實體 (SW 6.6.3+), Flysystem (公開/私有檔案儲存), Redis (快取/佇列), Rate Limiter (compiler pass + RateLimiter service), Data Indexer, Field Inheritance (變體), In-App Purchases
範例
examples/ 目錄中包含可執行的程式碼範例:
- examples/custom-entity/ — 可執行的 plugin:定義, 實體, 集合, 遷移, 版本化外部鍵到
product, 卸載清理 - examples/storefront-subscriber/ — 可執行的 plugin:頁面訂閱者, 銷售管道 repository, Twig 覆寫, 程式碼片段