Shopware 6 开发
核心架构
Shopware 6 是一个基于 PHP/Symfony 的电商平台。在生成代码前,请先确认目标层级:
| 层级 | 技术栈 | 位置 |
|---|---|---|
| 核心 / PHP | PHP 8.2+, Symfony 7.4 (SW 6.7) / Symfony 7.0 (SW 6.6) | src/ — 服务、DAL、事件 |
| 商店前端 | Twig 3, SCSS, Vanilla JS, Vite 开发服务器 (6.7.11+) | src/Resources/views/storefront/ |
| 后台管理 | Vue 3, Pinia, Meteor 组件 (mt-*), Vite 构建 | src/Resources/app/administration/ |
| 应用系统 (App System) | manifest.xml (6.7 中 schema 3.0), App Scripts | 外部服务器或 Twig 脚本 (无需 PHP) |
插件 (Plugin) vs 应用系统 (App System): 需要直接访问 PHP/数据库的自托管安装请使用插件。面向 SaaS/多租户或希望上架 Shopware 商店时,请使用应用系统。
使用哪个版本?
生成代码前,请询问或推断目标版本。当前版本线为 6.7.13.x;6.8 计划于 2027 年发布。6.7 对插件 API 做了大量破坏性变更,因此用于 6.6 的正确代码在 6.7 中往往是错误的:
| 主题 | SW 6.6 | SW 6.7 |
|---|---|---|
| 支付处理器 | Synchronous/AsynchronousPaymentHandlerInterface | AbstractPaymentHandler |
| 后台组件 | sw-button, sw-card, sw-text-field | mt-button, mt-card, mt-text-field |
| 后台状态管理 | Vuex Shopware.State (已弃用) | 仅限 Pinia Shopware.Store |
| 后台构建工具 | 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 的差异。
插件结构
PluginName/
├── composer.json
├── src/
│ ├── PluginName.php # 启动 (Bootstrap) 类
│ ├── Resources/
│ │ ├── config/
│ │ │ └── services.xml # Symfony 依赖注入容器
│ │ ├── views/
│ │ │ └── storefront/ # Twig 模板覆写
│ │ └── app/
│ │ └── administration/ # Vue.js 后台扩展
│ └── Migration/ # 数据库迁移
└── tests/
插件启动类
<?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. 监听事件 (订阅者)
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. 覆写商店前端模板
{# 镜像原始路径,位于 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 组件存在差异)
- 插件还是应用系统? 插件 = PHP 服务器;应用 = manifest.xml + 外部/无需服务器
- 层级? PHP/核心, 商店前端, 后台管理, 还是无头/商店 API
- 读还是写? 仓库的
search()vsupsert()/create()/update() - 实体还是扩展? 新建表 vs 扩展现有实体
只编写解决问题所需的最小代码。Shopware 的依赖注入和事件系统会处理大部分复杂性。
DAL 快速参考
// 条件查询
$criteria->addFilter(new EqualsFilter('active', true));
$criteria->addFilter(new ContainsFilter('name', '衬衫'));
$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::createDefaultContext(); // 系统上下文
// 或者从路由/事件中注入 SalesChannelContext
// 仅获取ID(更快,无需水合)
$ids = $this->repo->searchIds($criteria, $context)->getIds();
后台管理 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, 自定义字段, 实体扩展(扩展核心实体)
- references/admin.md — 后台管理:Vue 模块、组件、覆写、命名规范、ACL 权限、筛选/内联编辑、搜索配置
- references/storefront.md — 商店前端:Twig 继承、SCSS/主题变量、JavaScript 插件、控制器
- references/themes.md — 主题:theme.json(配置字段、颜色、字体、媒体)、SCSS Bootstrap 覆写、主题继承、ThemeInterface、CLI 命令
- references/cart.md — 购物车:CartDataCollector、CartProcessor、CartValidator + 自定义错误、折扣行项目、价格操作、税供应商
- references/seo-mail.md — SEO:SeoUrlRoute、站点地图 URL 提供器;邮件:自定义邮件模板(迁移 + 发送);文档(自定义 PDF 类型);订单状态机(转换、事件)
- references/plugin-structure.md — 完整插件结构:services.xml、生命周期钩子、composer.json、控制台命令、定时任务
- references/api.md — 后台 API 和商店 API:CRUD、批量操作、过滤器;上下文令牌生命周期、购物车/结账/账户商店 API、TypeScript 客户端模式
- references/testing.md — PHPUnit 单元/集成测试、StaticEntityRepository、ProductBuilder、Jest、Cypress、assertSame vs assertEquals
- references/app-system.md — 应用系统:manifest.xml、webhook HMAC 验证、注册握手、App Scripts(基于 Twig,无需服务器)
- references/security.md — 安全:路由作用域、CSRF 保护、输入验证、按客户授权、SQL 注入防护
- references/integrations.md — 集成:支付处理器 (
AbstractPaymentHandler)、运费(购物车处理器,而非计算器标签)、CMS 元素、规则生成器条件、Flow Builder 事件 - references/performance.md — 性能:HTTP 缓存(标签、失效)、消息队列(异步处理)、Elasticsearch/OpenSearch、对象缓存
- references/devops.md — DevOps:结构化日志、PHPStan、php-cs-fixer、CI/CD、部署、调试、媒体处理、升级安全
- references/migration-6.7.md — 6.6 到 6.7 迁移:核心/DAL、后台管理、商店前端、缓存、API、托管方面的破坏性变更,以及 6.7.x 新增内容(Vite 开发服务器、Twig UX 组件、MCP 服务器)
- references/advanced.md — 高级:PHP 属性实体 (SW 6.6.3+)、Flysystem(公共/私有文件存储)、Redis(缓存/队列)、速率限制器(编译器传递 + RateLimiter 服务)、数据索引器、字段继承(变体)、应用内购买
示例
examples/ 中包含可运行的代码示例:
- examples/custom-entity/ — 可运行插件:Definition、Entity、Collection、Migration、与
product的版本化外键、卸载清理 - examples/storefront-subscriber/ — 可运行插件:页面订阅者、销售渠道仓库、Twig 覆写、代码片段