How to add serializer in the services xml file?

I am trying to use Serializer Component in shopware 6 I have create a Serializer Class which I want to inject as DI in the controller.

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;
}

My problem is how to include this serializer in my services.xml file

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

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

Can anybody help. Thanks.

1 answer

  • answered 2021-01-11 06:58 Valerii Pravoslavnyi

    You need to define your Serializer as a service and inject it as an argument to Controller. For instance, if FQCN of your serializer is SwagMasterApi\Service\Serializer. You need to add the following code into your services.xml

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