如何在服务 xml 文件中添加序列化程序?

问题描述

我正在尝试在 Serializer 中使用 shopware 6 组件我创建了一个序列化器类,我想将其作为 DI 注入控制器中。

Serializer.PHP

class Serializer
{
    public function getSerializer(): Serializer
    {
        $encoder = [new JsonEncoder()];
        $normalizer = [new Objectnormalizer()];

        return new Serializer($normalizer,$encoder);
    }

}

MyController.PHP

public function __construct(Serializer $serializer)
{
    $this->serializer = $serializer;
}

我的问题是如何在我的 services.xml 文件中包含这个序列化程序

<service id="SwagMasterapi\Core\Api\MyController" public="true">

            <call method="setContainer">
                <argument type="service" id="service_container"/>
            </call>
<service>

谁能帮忙。谢谢。

解决方法

您需要将序列化程序定义为服务并将其作为参数注入控制器。例如,如果您的序列化程序的 FQCN 是 SwagMasterApi\Service\Serializer。您需要将以下代码添加到您的 services.xml 中

<service id="SwagMasterApi\Service\Serializer">
<service>

<service id="SwagMasterApi\Core\Api\MyController" public="true">
    <argument type="service" id="SwagMasterApi\Service\Serializer" />
<service>