Dieses Blog durchsuchen

Sonntag, 17. Juli 2016

symfony 3: use custom repositories instead of entities

Its allways a good idea, not to use entitiyobject like $user= new User();

Symfony allows to implement the repositorypattern. Its well documented and a good way, to extend the entities without to couple the entityclass and the manager

In the next example I want to show you not only to implement the repository. I have implemented an AbstractRepository and a repositoryInterface too to setup an extendable abstract repositorymechanismto


1) first thing to do is creating a folder "Entities" in your Bundle
2) Save a File called "UserRepository.php"
3) Save a FIle EntityRepositoryAbstract.php
4) Save a File IEntityRepository.php

My abstract repository implements 2 methods to make saving objects easier, when requests come from an api controller

At next we implement the interface:

At next we implement a UserRepository. This Class is empty for now. Because the current save implementation can be used abstract
To make this work, we have to tell the entity, that it has to use our new repositories. This can be done by setting the right annotations.
Here is my entityclas. As you can see we have extended the Anntotation ORM\ENTITY with the link to our new repository
* @ORM\Entity(repositoryClass="Check\BlogBundle\Repositories\UserRepository")

At next you have to delete all genereated .orm files under src//Resoucres/config/doctrine and clear your appcache,otherwise it want work.
At last we can use our new UserRepository like that in a controller. This apicontroller takes a request and saves the body as a new user directly via calling a save() method in our new repository

Keine Kommentare:

Kommentar veröffentlichen