使用 symfony 序列化器组也不起作用

问题描述 投票:0回答:1

我正在使用 slim4 框架和 php8.3 开发一个应用程序。 我安装了 symfony 序列化器来序列化/反序列化我的对象。

这就是我像依赖项一样创建序列化器的方式:

dependencices.php

$containerBuilder->addDefinitions([
        Serializer::class => function () {
            $encoders = [new JsonEncoder()];
            $extractors = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]);
            $normalizers = [new ArrayDenormalizer(), new ObjectNormalizer(null, null, null, $extractors)];

            return new Serializer($normalizers, $encoders);
        }
    ]);

这是我的实体:

<?php

namespace App\Domain\Entity;

use App\Application\Repository\CompanyRepository;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Table;
use Symfony\Component\Serializer\Annotation\Groups;

#[Entity(repositoryClass: CompanyRepository::class), Table(name: 'companies')]
class Company
{
    #[Groups(['save-company'])]
    #[Column(type: 'string', length: 9, nullable: true)]
    private string $siren;

    #[Groups(['save-company'])]
    #[Column(type: 'string', length: 15, nullable: true)]
    private string $siret;

    #[Column(name: 'trading_name', type: 'string', length: 50, nullable: true)]
    private ?string $tradingName;


    public function getSiren(): string
    {
        return $this->siren;
    }

    public function setSiren(string $siren): void
    {
        $this->siren = $siren;
    }

    public function getSiret(): string
    {
        return $this->siret;
    }

    public function setSiret(string $siret): void
    {
        $this->siret = $siret;
    }

    public function getTradingName(): ?string
    {
        return $this->tradingName;
    }

    public function setTradingName(?string $tradingName): void
    {
        $this->tradingName = $tradingName;
    }

}

这就是我反序列化对象的方式:

$this->sfSerializer->deserialize(json_encode($this->getFormData()), Company::class, JsonEncoder::FORMAT, [
            AbstractNormalizer::OBJECT_TO_POPULATE => $company,
            AbstractNormalizer::GROUPS => ['save-company']
        ]);

这是请求的正文:

{
        "siren": "SRN-1",
        "siret": "SRT-1",
        "tradingName": "my comany name"
}

我想要的是序列化器仅反序列化警报器和 Siret,但它反序列化所有属性。 我缺少什么?

symfony deserialization slim-4
1个回答
0
投票

尝试在您不想序列化的字段上使用实体中的 #Ignore 属性:

#[Column(name: 'trading_name', type: 'string', length: 50, nullable: true)]
#Ignore
private ?string $tradingName;
© www.soinside.com 2019 - 2024. All rights reserved.