0

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

0

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Eventually I decided not to save these data (these are tiny objects so I always build them on the fly), but your answer is helpful nonetheless and I will gladly use it in future. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.