R
R
Roman2017-09-13 19:19:08
symfony
Roman, 2017-09-13 19:19:08

Dynamic data in JsonApi from Doctrine-Model - how?

Good time, colleagues!
Available : Symfony 3.3, Doctrine 2.5, Neomerx/JsonApi 1.0.
Now : The User model has tabs (you can add different types of entities to them, including other users). With Doctrine and the IFavouritable interface, they are represented as a one-to-many relationship like this:

trait HasFavorites
{
    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\Favorite", mappedBy="user")
     */
    protected $favorites;

    public function getFavorites() : Collection { return $this->favorites; }
    public function addFavorite(Favorite $favorite) { $this->favorites->add($favorite); }
    public function removeFavorite(Favorite $favorite) { $this->favorites->removeElement($favorite); }
}

Now, in the schema (=serializer?), just before the response is returned, I have a User object, which I turn into an array, and then into json.
Question : in models with an interface, you need to give the value "is this object in the bookmarks of the current logged in user". How would you decide?
Options :
- Using DI, add a repository and an authenticator to the schema, make requests with verification from the schema. I do not like this option because when returning 100 objects, there will be 100+ requests to the database to clarify this attribute.
– Pass the repository and the current user to the model. The problems are the same as in the example above, plus the model begins to know about the storage.
– ???

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2017-09-13
@TrogWarZ

I am for the first option:
- Inject a repository with favorites into the OrderNormalizer
- When serializing the entity, we pull out all the favorites of the logged in user and put them in the cache
- During subsequent serialization, after the favorites, we already go to the cache, and not to the database

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question