You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopware 6:如何通过自动装配注入实体仓库

Shopware 6 用Symfony自动装配替代传统实体仓库注入的等效写法

传统通过services.xml注入实体仓库的写法你已经清楚了,下面是两种用Symfony自动装配实现相同效果的方式,核心是告诉Symfony要注入的是product.repository这个具体服务,而非泛型的EntityRepository:

方式一:用#[Autowire]注解直接指定服务ID

这是最直接的方式,在构造函数参数上通过注解明确绑定服务ID,不需要在services.xml里写<argument>标签,只要服务开启自动装配即可:

PHP代码(服务/控制器类)

use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;

class YourServiceOrController
{
    private EntityRepository $productRepository;

    public function __construct(
        #[Autowire(service: 'product.repository')]
        EntityRepository $productRepository
    ) {
        $this->productRepository = $productRepository;
    }

    // 其他业务方法...
}

对应的services.xml配置

<!-- 只需开启autowire,无需手动声明参数 -->
<service id="Your\Service\Or\Controller\Namespace" autowire="true">
</service>

方式二:在services.xml中用bind配置全局绑定

如果多个服务都需要注入同一个实体仓库,或者不想在代码里加注解,可以在services.xml的服务配置里用bind参数绑定类型+参数名到具体服务ID:

services.xml配置

<service id="Your\Service\Or\Controller\Namespace" autowire="true">
    <bind>
        <!-- 格式:类型 变量名 => @服务ID -->
        <parameter key="Shopware\Core\Framework\DataAbstractionLayer\EntityRepository $productRepository">@product.repository</parameter>
    </bind>
</service>

对应的PHP代码(服务/控制器类)

代码可以简化,直接保留类型提示和参数名即可,Symfony会自动根据bind配置注入正确的服务:

use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;

class YourServiceOrController
{
    private EntityRepository $productRepository;

    public function __construct(
        EntityRepository $productRepository
    ) {
        $this->productRepository = $productRepository;
    }

    // 其他业务方法...
}

注意:如果你的服务是通过_defaults标签全局开启了autowire="true",那单个服务配置里可以不用重复声明autowire="true"。

内容的提问来源于stack exchange,提问作者Benny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 09:40:06