【问题标题】:Deserializing indexed array of object in Symfony在 Symfony 中反序列化对象的索引数组
【发布时间】:2020-09-06 08:29:59
【问题描述】:

我需要从 YAML 文件中反序列化对象的索引数组。问题是 symfony 认为它是items 中的一堆对象,但它是带有索引的数组,并且总会有不同的名称(索引)。我在文档中找不到答案(很确定我只是忽略了)。

有什么建议吗?

YAML:

items:
  darkvoice:
    display_name: Dark Voice
    price: 100
  phone:
    display_name: Mobile phone
    price: 100

映射

$encoders = [ new YamlEncoder() ];
$normalizers = [
    new ObjectNormalizer(null, null, null, new ReflectionExtractor()),
];
$serializer = new Serializer($normalizers, $encoders);
$test = $serializer->deserialize(file_get_contents(__DIR__.'/example.yml'), ItemList::class, 'yaml');

class ItemList {

    /** @var Singleton[] */
    private array $items = [];

    /**
     * @return Singleton[]
     */
    public function getItems(): array
    {
        return $this->items;
    }

    /**
     * @param Singleton[] $items
     * @return ItemList
     */
    public function setItems($items): self
    {
        $this->items = $items;
        return $this;
    }
}

class Singleton {

    private string $display_name;
    private int $price = 0;

    /**
     * @return string
     */
    public function getDisplayName(): string
    {
        return $this->display_name;
    }

    /**
     * @param string $display_name
     * @return Singleton
     */
    public function setDisplayName($display_name):self
    {
        $this->display_name = $display_name;
        return $this;
    }

    /**
     * @return int
     */
    public function getPrice(): int
    {
        return $this->price;
    }

    /**
     * @param int $price
     * @return Singleton
     */
    public function setPrice(int $price): Singleton
    {
        $this->price = $price;
        return $this;
    }
}

【问题讨论】:

标签: php symfony serialization


【解决方案1】:

您可以像这样添加到您的 services.yaml 文件中:

parameters:
    items: {
        darkvoice: {
            display_name: Dark Voice
            price: 100
        },
        phone: {
            display_name: Mobile phone
            price: 100
        }
    }

然后在控制器中你可以通过添加来访问参数:

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

在构造函数中自动连接它:

public function __construct(ParameterBagInterface $params)
{
    $this->getItems = $params->get('items');
}

不确定这是否会对您有所帮助,或者给您一些额外的考虑以适应您的情况..

【讨论】:

    猜你喜欢
    • 2023-01-11
    • 2018-04-26
    • 2018-09-21
    • 2018-08-16
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 2015-08-10
    • 2017-08-28
    相关资源
    最近更新 更多