简体   繁体   中英

How to use Repository without associate to an Entity class in symfony 2.8

I would like logic like the following: -> controller- > call to Model class (that extend model with the entity,manager)- > the function in model will call to getRepository() and use funcion that dealing with the DB.

How can I do that? When I call to Repository I must have an entity, and if I have an empty entity the error is that I must have primary column with id.

As the first comment says, you should not call the repository directly from the entity class. You have several options here (descending by the code quality)

Refine the logic to invert the control flow

Define a service, which accepts the entity, the repository and does the stuff

$service = new EntityStuffService($repository);
$service->doTheStuff($entity);

Declare a relation

Just declare a realtion within your class and filter it manually. Doctrine PersistentCollection implements Selectable , so you can just filter it using the ->matching($criteria) call.

http://doctrine-orm.readthedocs.io/en/latest/reference/working-with-associations.html#filtering-collections

The ugliest way

Doctrine has the ObjectManagerAware interface, which allows you to inject the object manager into the entity on hydation completion. This will allow you to implement and kind of AR patters and other spaghetti-code and I strongly recommend you not to do this.

https://github.com/doctrine/common/blob/master/lib/Doctrine/Common/Persistence/ObjectManagerAware.php

You can implement this interface and store the ObjectManager inside the entity to do any kind of operations with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM