Shopware自定义ReadingData服务构造函数参数不足报错排查
报错原因
报错是两个问题叠加导致的:
- 服务配置和类构造函数的参数数量不匹配:
ReadingData类的构造函数声明了2个必填入参,但services.xml中定义TryPlugin\Service\ReadingData服务时,只传入了product.repository1个参数,依赖注入容器实例化服务时参数不足,直接触发报错。 - 依赖用法错误:Shopware中的
Context是和单次请求/执行流程绑定的动态上下文对象,不是容器全局托管的单例服务,不能通过构造函数注入到服务中——即使你在services.xml里补上第二个Context类型的参数,容器也会因为找不到对应服务抛出新的错误,同时构造注入固定的Context也会在后续使用中出现上下文不匹配的逻辑问题。
另外原代码里readData方法声明为void返回值,没有把查询到的产品结果返回,控制器拿不到查询数据,属于后续会触发的逻辑bug,可同步修复。
修复方法
按照以下步骤调整代码即可:
- 调整
ReadingData类,移除构造函数中的Context依赖,将Context改为readData方法的入参,同时补上方法返回值:
use Shopware\Core\Framework\Context; use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface; use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; class ReadingData { private EntityRepositoryInterface $productRepository; public function __construct(EntityRepositoryInterface $productRepository) { $this->productRepository = $productRepository; } public function readData(Context $con) { $criteria1 = new Criteria(); return $this->productRepository->search($criteria1, $con)->getEntities(); } }
- 调整控制器方法,通过控制器参数解析直接获取当前请求对应的Context实例,传入服务方法:
use Shopware\Core\Framework\Context; /** * @RouteScope (scopes={"storefront"}) */ class PageController extends StorefrontController { /** * @Route("/examples", name="examples", methods={"GET"}) */ public function showExample(ReadingData $ReadingDatan, Context $context): Response { $meinData = $ReadingDatan->readData($context); return $this->renderStorefront('@Storefront/storefront/page/content/index.html.twig', [ 'products' => $meinData, ]); } }
- 现有
services.xml的配置已经匹配修改后的构造函数参数,不需要调整。修改完成后执行bin/console cache:clear清空项目缓存,避免旧的容器缓存影响代码生效。
内容的提问来源于stack exchange,提问作者Samee
相关产品推荐
相关产品推荐

