Search code examples
symfonyserializationdoctrine-ormsymfony5php-8

symfony doctrine2 store entity as json


I have an entity with several properties that could be grouped together, are crucial for it's usage and I won't ever have to index them.
I thought about storing them in separate class, just for the order.
I'd like to store the object of this class inside a text column in a json representation.
I tried something like this:

class Market
{
    /**
     * @var Fee
     * @ORM\Column(type="json")
     */
    protected Fee $fee;
(...)
}

and the Fee class:

class Fee implements Serializable
{
    private float $taker;
    private float $maker;

    public function __construct(float $taker, float $maker)
    {
        $this->taker = $taker;
        $this->maker = $maker;
    }

    /**
     * @return float
     */
    public function getTaker(): float
    {
        return $this->taker;
    }

    /**
     * @return float
     */
    public function getMaker(): float
    {
        return $this->maker;
    }

    public function serialize()
    {
        return json_encode(
            [
                'taker' => $this->getTaker(),
                'maker' => $this->getMaker(),
            ]
        );
    }

    public function unserialize($serialized)
    {
        $decoded = json_decode($serialized, true);
        $this->taker = $decoded['taker'];
        $this->maker = $decoded['maker'];
    }
}

I'd like to have something like this in final column "fee":

{
 "taker": 0.0016,
 "maker": 0.004
}

but instead I always get an empty json {}.
Please advise how to do what I intend to.
I'm using Symfony 5.3.6 with PHP 8.0.9


Solution

  • You used a JSON field type, which expects an array instead of a string. So you shouldn't serialize it before setting.

    You can use a object type instead:

    class Market
    {
        /**
         * @ORM\Column(type="object")
         */
        protected Fee $fee;
    }
    

    (I also removed @var Fee because it's superfluous)