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

Shopware 6自定义API依赖注入报错:服务不存在原因排查

问题描述

在Shopware 6中创建自定义API端点以根据订单ID获取订单详情时,注入OrderService服务后系统抛出错误:

The service "SomthingContoller" has a dependency on a non-existent service "Swag\PluginName\Service\OrderService"

即使已在service.xml中配置控制器的构造函数参数,该报错仍持续出现。相关文件代码如下:

src/Storefront/Controller/SomethingController.php

<?php declare(strict_types=1);

namespace Swag\PluginName\Storefront\Controller;

use Symfony\Component\Routing\Annotation\Route;
use Swag\PluginName\Service\OrderService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Shopware\Core\Framework\Context;

/**
 *
 * @Route(defaults={"_routeScope"={"api"}})
 */
class SomethingController extends AbstractController
{
    public $orderService;

    public function __construct(
        OrderService $orderService
    )
    {
        $this->orderService = $orderService;
    }

    /**
    * @Route("/api/orderconfig/{orderId}", name="api.something.orderconfig", methods={"GET"})
    * @param string $orderId
    * @return JsonResponse
    */
    public function orderConfig(string $orderId): JsonResponse
    {
        $order = $this->orderService->getOrder($orderId, Context::createDefaultContext());
        return $order;
    }
}

src/Service/OrderService.php

<?php

namespace Swag\PluginName\Service;

use Psr\Log\LoggerInterface;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Checkout\Order\OrderEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;

class OrderService
{
    /**
     * @var EntityRepositoryInterface
     */
    private $orderRepository;


    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * OrderRepository Constructor
     * 
     * @param EntityRepositoryInterface $orderRepository
     * @param LoggerInterface $logger
     */
    public function __construct(
        EntityRepositoryInterface $orderRepository,
        LoggerInterface $logger
    )
    {
        $this->orderRepository = $orderRepository;
        $this->logger = $logger;
    }

    /**
     * @param string $orderId
     * @param Context $context
     * @param array $associations
     * @return OrderEntity|null
     */
    public function getOrder(string $orderId, Context $context, array $associations = []): ?OrderEntity
    {
        $order = null;

        try {
            $criteria = new Criteria();
            $criteria->addFilter(new EqualsFilter('id', $orderId));

            /** @var OrderEntity $order */
            $order = $this->getOrderByCriteria($criteria, $context, $associations);
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage(), [$e]);
        }

        return $order;
    }

    public function getOrderByCriteria(Criteria $criteria, Context $context, array $associations = []): ?OrderEntity
    {
        foreach ($associations as $association) {
            $criteria->addAssociation($association);
        }
        return $this->orderRepository->search($criteria, $context)->first();
    }

    public function getOrderByOrderNumber(string $orderNumber, Context $context, array $associations = []): ?OrderEntity
    {
        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('orderNumber', $orderNumber));

        return $this->getOrderByCriteria($criteria, $context, $associations);
    }

    public function update(string $orderId, array $data, Context $context)
    {
        $data['id'] = $orderId;
        $this->orderRepository->update([$data], $context);
    }
}

src/Resources/config/services.xml

<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="Swag\PluginName\Storefront\Controller\SomethingController" public="true">
            <argument type="service" id="Swag\PluginName\Service\OrderService"/>
            <call method="setContainer">
                <argument type="service" id="service_container"/>
            </call>
        </service>
    </services>
</container>
原因及解决办法

核心原因

  1. OrderService未注册为Symfony服务:仅在services.xml中配置了控制器的依赖,但未将OrderService本身注册到依赖注入容器,导致容器无法找到该服务实例。
  2. 控制器类名拼写错误:报错信息中的SomthingContoller少了字母e,正确类名应为SomethingController,拼写错误会导致容器匹配不到正确的控制器服务。
  3. 控制器返回值类型不匹配:orderConfig方法声明返回JsonResponse,但实际返回OrderEntity对象,会触发类型错误。

解决步骤

1. 注册OrderService到services.xml

修改配置文件,添加OrderService的服务定义,并注入它依赖的order.repository和logger服务:

<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <!-- 注册OrderService -->
        <service id="Swag\PluginName\Service\OrderService">
            <argument type="service" id="order.repository"/>
            <argument type="service" id="logger"/>
        </service>

        <service id="Swag\PluginName\Storefront\Controller\SomethingController" public="true">
            <argument type="service" id="Swag\PluginName\Service\OrderService"/>
            <call method="setContainer">
                <argument type="service" id="service_container"/>
            </call>
        </service>
    </services>
</container>

2. 修正控制器类名拼写

检查所有涉及控制器类名的位置(路由注解、服务配置等),确保统一为SomethingController,避免拼写不一致。

3. 修正控制器返回值

将orderConfig方法的返回值改为符合声明类型的JsonResponse,使用$this->json()方法转换实体对象:

public function orderConfig(string $orderId): JsonResponse
{
    $order = $this->orderService->getOrder($orderId, Context::createDefaultContext());
    return $this->json($order);
}

4. 清理缓存

执行Shopware缓存清理命令,确保新的服务配置生效:

bin/console cache:clear

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:05:23