I am stuck with a problem please help me with it. Here is the scenarario:
I have an entity "User" and corresponding repository "UserRepository", inside my entity there are only getter and setter methods. All custom queries I have written to UserRepository. Now inside my UserController I am trying to access repository methods which I am not able to do so.
e.g.
User entity:
class User
{
...
public function getId()
{
return $this->id;
}
public function setId($id)
{
return $this->id=$id;
}
public function setProperty($property)
{
$this->property = $property;
}
public function getProperty()
{
return $this->property;
}
....
}
?>
UserRepository:
class UserRepository extends EntityRepository
{
public function findUsersListingById($id)
{
$queryBuilder = $this->getEntityManager()->createQueryBuilder();
$query = $em->createQuery(
"SELECT U
FROM UserEntityPathGoesHere
WHERE U.id IN (".implode(",", $id).")"
);
$users = $query->getResult();
return $users;
}
public function sayHelloWorld(){
echo ' Hello World';
}
}
?>
UserController
class UserController
{
...
$users=$this->getDoctrine()
->getRepository('MyUserEntityPath')
->findUsersListingById($ids);
//now I have multiple users I want to iterate through each user for associating additional data with each user
foreach($users as $user)
{
$temp = array();
//I am able to access getId method which is defined in User entity
$temp['id'] = $user->getId();
//however I am not able to access method from UserRepository, I tried something like below which gives me error call to undefined function sayHelloWorld
$temp['status'] = $user->sayHelloWorld();
....
}
}
....
How can I access repository methods for an entity? Is it possible ? If not then what are the alternatives for the solution?
Everything is possible however you should not access the entity's repository from the entity itself because of the separation of concerns.
See this Stackoverflow answer for more details.
Basically, the whole idea is that you want to have your application organized the following way.
In short:
Controller > Repository > Entities.
It should not go in the other direction otherwise it creates a mess.
If you want to go a bit further into the separation of concerns you could do the following.
Controller > Service > Repository > Entities
Alternative solutions:
Create a Twig extension that access a service (which access a repository) or a repository.
Create a method in your repository, call the method in your controller, map the data to IDs (keys of array are the IDs), pass the array to the template and then pull the data from the array using the entity IDs
Create a method in your repository, call the method in your controller, inject the data into your entities and access the data through the entity in your template.
There are probably others but you would know better how your application is organized.
If the bundle is Acme/DemoBundle, then one would expect at a minimum
User entity
namespace Acme/DemoBundle/Entity
use Doctrine\ORM\Mapping as ORM;
/**
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="Acme/DemoBundle/Entity/UserRepository")
*/
class User
{
...
}
User repository
namespace Acme/DemoBundle/Entity
use Doctrine\ORM\Mapping as ORM;
class UserRepository extends EntityRepository
{
...
}
It is also true that with an array of ids, one can also do the following in a controller:
...
$em = $this->getDoctrine()->getManager();
$users = $em->getRepository("AcmeDemoBundle:User")->findAllById($idArray);
...
To iterate thru users in a controller, one can then use a foreach loop as in:
foreach ($users as $user) {
//each user is an array
...
$id = $user['id'];
...
}
or in a template:
{% for user in users %}
...
{{ user.firstName }}
...
{% endfor %}
You need to declare the UserRepository as an EntityRepository for your user entity. In your User entity add this annotation:
/**
* #ORM\Entity(repositoryClass="Acme\StoreBundle\Entity\UserRepository")
*/
See the docs for a more detailed description.
You can use the postLoad event from doctrine and inject everything you want into the entity. The event listener looks like:
<?php
namespace AppBundle\EventListener;
use AppBundle\Entity\MyEntity;
use Doctrine\ORM\Event\LifecycleEventArgs;
/**
* Class MyEntityListener
*/
class MyEntityListener
{
public function postLoad(LifecycleEventArgs $eventArgs)
{
/** #var MyEntity $document */
$document = $eventArgs->getEntity();
if(!($document instanceof MyEntity)){
return;
}
$document->setEntityManager($eventArgs->getEntityManager());
}
}
and service.yml:
services:
app.myentity.listener:
class: AppBundle\EventListener\MyEntityListener
tags:
- { name: doctrine.event_listener, event: postLoad }
Of cource your Entity needs the method setEntityManager and your're ready.
Related
I have a basic Doctrine2 entity, but one of the fields needs some formatting applied to it to turn it from a database primary key, into a user-visible "friendly ID".
I want to put the formatting logic in only one place, so that if it ever changes, it only has to be updated once.
Part of the formatting involves looking up a string from the database and using that as a prefix, as this value will be different for different installations. I am a bit stuck, because within the entity I can't (and probably shouldn't) look up the database to retrieve this prefix.
However I am not sure how else to go about this.
Here is some pseudocode illustrating what I am trying to do:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serializer;
// This is also an entity, annotations/getters/setters omitted for brevity.
class Lookup {
protected $key;
protected $value;
}
class Person {
/**
* Database primary key
*
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* Get the person's display ID.
*
* #Serializer\VirtualProperty
* #Serializer\SerializedName("friendlyId")
*/
protected function getFriendlyId()
{
if ($this->person === null) return null;
//$prefix = 'ABC';
// The prefix should be loaded from the DB, somehow
$lookup = $this->getDoctrine()->getRepository('AppBundle:Lookup')->find('USER_PREFIX');
$prefix = $lookup->getValue();
return $prefix . $this->person->getId();
}
}
You could use event listeners using symfony and doctrine and listen to postLoad event by registering the service
services:
person.postload.listener:
class: AppBundle\EventListener\PersonPostLoadListener
tags:
- { name: doctrine.event_listener, event: postLoad }
Now in your listener you will have an access to entity manager
namespace AppBundle\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use AppBundle\Entity\Person;
class PersonPostLoadListener
{
public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof Person) {
return;
}
$entityManager = $args->getEntityManager();
$lookup =$entityManager->getRepository('AppBundle\Entity\Lookup')->findOneBy(array(
'key'=> 'USER_PREFIX'
));
$entity->setFriendlyId($entity->getId().$lookup->getValue());
//echo "<pre>";dump($entity);echo "</pre>";die('Call')
}
}
And in your person entity you need to define an un mapped property for your id and its getter and setter method like
class Person
{
private $friendlyId;
public function getFriendlyId()
{
return $this->friendlyId;
}
public function setFriendlyId($friendlyId)
{
return $this->friendlyId = $friendlyId;
}
}
All of my query in Entity Repository needs to be filtered by user.
Now I want to know how can I access the currently logged in user in Entity Repository directly.
What I did today is to get the currently logged in user in my controller, through the use of $this->getUser() and then pass it to Entity Repository and this is not efficient.
You need to inject security.token_storage service into another one to get the current user, but as of Repository classes belong to Doctrine project, not Symfony, it is not recommended to do this.. May be there is a way to achieve it by creating custom entityManager class as described here, but I don't think it would a good solution..
Instead of customizing an entityManager better create a service which calls repository classes' methods, inject desired services into it.. Let Repository classes do their job.
Implementation would be something like this:
RepositoryClass:
class MyRepository extends EntityRepository
{
public function fetchSomeDataByUser(UserInterface $user)
{
// query
}
}
Service:
class MyService
{
private $tokenStorage;
public function _construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
// other services
}
public function getSomeDataByUser()
{
$user = $this->tokenStorage->getToken()->getUser();
return $this->entityManager->getRepository(MyREPOSITORY)->fetchSomeDataByUser($user);
}
}
Usage:
public function someAction()
{
$dataByUser = $this->get(MYSERVICE)->getSomeDataByUser();
}
If you use JMSDiExtraBundle it can be done by adding setter injection:
use Doctrine\ORM\EntityRepository;
use JMS\DiExtraBundle\Annotation as DI;
class YourRepository extends EntityRepository
{
/** #var User current user entity */
protected $user;
/**
* #DI\InjectParams({
* "token_storage" = #DI\Inject("security.token_storage")
* })
*/
public function setSimplaManager(TokenStorageInterface $tokenStorage)
{
$token = $tokenStorage->getToken();
if (!is_object($user = $token->getUser())) {
// e.g. anonymous authentication
return;
}
$this->user = $user;
}
}
I have a User Entity class and I craete a UserRepository.php in the same directory to put my custom methods in it, But when I use that in a contoller using this syntax it won't work:
my Repository:
namespace Doobin\UserBundle\Entity;
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
public function pageAccess($User=1,$Page='_home')
{
$stmt="Somthing to test";
return $stmt;
}
}
My controller to use repository:
use Doobin\UserBundle\Entity\User;
.
.
.
.
$em = $this->getDoctrine()->getManager();
$products = $em->getRepository('UserBundle:User')->pageAccess();
var_dump($products);
When I use it, It counld't find the pageAccess method.
Should I introduce the repository somewhere? becuase the tuturial itself didn't say anything.
In your User entity you should add annotation on the top of the class :
/**
* User.
*
* #ORM\Table(name="my_user")
* #ORM\Entity(repositoryClass="UserRepository")
*/
class User
{
}
With propel we have findOneOrCreate()
Example.
$bookTag = BookTagQuery::create()
->filterByBook($book)
->findOneOrCreate();
In doctrine anywhere in the controller We can do something like that.
...................
$filename='something';
$document_exists = $em->getRepository('DemoBundle:Document')
->findOneBy(array('filename' => $filename));
if (null === $document_exists) {
$document = new Document();
$document->setFilename($filename);
$em->persist($document);
$em->flush();
}
Is there another way to achieve this in Doctrine?
Is it OK to call the Entity Manager inside the Entity Repository?
Any suggestions?
Easiest way is to extend the base repository:
// src/Acme/YourBundle/Entity/YourRepository.php
namespace Acme\YourBundle\Entity;
use Doctrine\ORM\EntityRepository;
class YourRepository extends EntityRepository
{
public function findOneOrCreate(array $criteria)
{
$entity = $this->findOneBy($criteria);
if (null === $entity)
{
$entity = new $this->getClassName();
$entity->setTheDataSomehow($criteria);
$this->_em->persist($entity);
$this->_em->flush();
}
return $entity
}
}
Then tell your entity to use this repository or extend in even further for specific entities:
// src/Acme/StoreBundle/Entity/Product.php
namespace Acme\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="Acme\YourBundle\Entity\YourRepository")
*/
class Product
{
//...
}
and use it in your controller:
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('AcmeStoreBundle:Product')
->findOrCreate(array('foo' => 'Bar'));
Source: http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes
Just be aware of that flush inside the repository as it would flush all unsaved changes in the EntityManager this way.
Have a look at the constructor of Doctrine\ORM\Repository here.
The EntityManager is mandatory for constructing a repository. The manager can - by default - not be accessed directly from a repository object because the property _em and the getter function getEntityManager are protected.
but ... yes, sure it is "OK" to call the EntityManager via the _em property inside a repository. All the other methods like findBy, ... etc. use it aswell and need the entity-manager to work actually :)
/**
* #var EntityManager
*/
protected $_em;
public function __construct($em, Mapping\ClassMetadata $class)
{
$this->_entityName = $class->name;
$this->_em = $em;
$this->_class = $class;
}
/**
* #return EntityManager
*/
protected function getEntityManager()
{
return $this->_em;
}
You can easily add a findOneOrCreate method to your entity repository or create a generic extended repository including that method.
then you can extend this new base repository whenever you need the method in a concrete entity repository.
I'd like to use, something like:
$em = $this->getEntityManager();
Inside a Entity.
I understand I should do this as a service but for some testing purposes, I want to access it from an Entity.
Is it possible to achieve that?
I've tried to:
$em = $this->getEntityManager();
$profile_avatar = $em->getRepository('bundle:Perfils')->findOneByUser($this-getId());
But isn't working.
Fatal error: Call to undefined method
Proxies\webBundleEntityUserProxy::getEntityManager() in
/opt/lampp/htdocs/web/src/Pct/bundle/Entity/User.php on line
449
Why am I trying to do it this way?
I've 3 kinds of users: Facebook, Twitter and MyOwnWebsite users. Each of them have differents avatar which links facebook's profile, twitter's or otherwise, if its myownwebsite user, I retrieve the avatar from a URL in a database. For now, I don't want to create a service, because I'm just trying to make it working, to test it, not to create a final deployment. So this is why I'm trying to call Entity manager from an Entity. I don't want, by now, to modify configuration files, just this entity.
As pointed out (again) by a commenter, an entity manager inside an entity is a code smell. For the OP's specific situation where he wished to acquire the entity manager, with the least bother, a simple setter injection would be most reliable (contrary to my original example injecting via constructor).
For anyone else ending up here looking for a superior solution to the same problem, there are 2 ways to achieve this:
Implementing the ObjectManagerAware interface as suggested by https://stackoverflow.com/a/24766285/1349295
use Doctrine\Common\Persistence\ObjectManagerAware;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class Entity implements ObjectManagerAware
{
public function injectObjectManager(
ObjectManager $objectManager,
ClassMetadata $classMetadata
) {
$this->em = $objectManager;
}
}
Or, using the #postLoad/#postPersist life cycle callbacks and acquiring the entity manager using the LifecycleEventArgs argument as suggested by https://stackoverflow.com/a/23793897/1349295
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks()
*/
class Entity
{
/**
* #ORM\PostLoad
* #ORM\PostPersist
*/
public function fetchEntityManager(LifecycleEventArgs $args)
{
$this->setEntityManager($args->getEntityManager());
}
}
Original answer
Using an EntityManager from within an Entity is VERY BAD PRACTICE. Doing so defeats the purpose of decoupling query and persist operations from the entity itself.
But, if you really, really, really need an entity manager in an entity and cannot do otherwise then inject it into the entity.
class Entity
{
private $em;
public function __contruct($em)
{
$this->em = $em;
}
}
Then invoke as new Entity($em).
Best way is to use Life Cycle: #ORM\HasLifecycleCallbacks
And you can use the appropriate Event as you want to get result:
#postLoad
#postPersist
...
Calling the Entity Manager from inside an Entity is a bad practice! You should keep your entities as simple as possible.
For what purpose do you need to call the Entity Manager from an Entity?
What I think you should do is, instead of using the Entity Manager inside your entity, is to create a custom repository for your entity.
In your entity ORM file, add an entry as follows (or in your entity class annotations if not using YML):
App\Bundle\Profils:
# Replace the above as appropiate
type: entity
table: (your table)
....
repositoryClass: App\Bundle\CustomRepos\ProfilsRepository
# Replace the above as appropiate.
# I always put my custom repos in a common folder,
# such as CustomRepos
Now, create a new PHP class that has the namespace above:
//Your ProfilsRepository.php
<?php
namespace App\Bundle\CustomRepos;
use Doctrine\ORM\EntityRepository;
class ProfilsRepository extends EntityRepository
{
/**
* Will return the user url avatar given the user ID
* #param integer $userID The user id.
#return string The avatar url
*/
public function getUserProfile($userId)
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$qb->select... (your logic to retrieve the profil object);
$query = $qb->getQuery();
$result = $query->getResult();
return $result;
}
}
Finally, in your Controller:
// Your controller
<?php
namespace <class namespace>;
...
use App\Bundle\CustomRepos\ProfilsRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
...
class YourClassNameController extends Controller
{
public function yourAction()
{
$userId = <get the user ID>;
// Pass the name of your entity manager to the
// getManager function if you have more than one and
// didn't define any default
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('Profils');
$avatar = $repo->getUserProfile($userId);
...
}
}
You need to set the services.yml with:
services:
your_service_name:
class: AppBundle\Controller\ServiceController
arguments: [ #doctrine.orm.entity_manager ]
You need to set also the Controller with the following constructor:
public function __construct(\Doctrine\ORM\EntityManager $em)
{
$this->em = $em;
}
and use $this->em in the controller
(for example $connection = $this->em->getConnection();)