KFCSpike
KFCSpike

Reputation: 90

Symfony2/Doctrine2 How to move a function from Entity to Repository

I have a function in my Entity (User.php) that counts the unread Alerts for the User:

public function getCountUnreadAlerts()
{
    $countUnread = 0;
    $alerts = $this->getAlertsReceived();
    foreach ($alerts as $alert)
    {
        if (!$alert->getReadbyreceiver())
        {
            $countUnread ++;
        }
    }
    return $countUnread;
}

It works fine, I can use the getCountUnreadAlerts() function in controllers and app.user.getCountUnreadAlerts in twig templates. All well and good, but my understanding is that functions like that shouldn't really be part of the Entity and better placed in a Repository?

My User Entity is set up with Annotations to point to my UserRepository...

* @ORM\Entity(repositoryClass="MyCompany\BlogBundle\Repository\UserRepository")

My question is, how do I move that function into my UserRepository.php? My attempts so far (pasting the function directly into UserRepository) have resulted in error messages saying that the Method "getCountUnreadAlerts" does not exist.

Upvotes: 0

Views: 226

Answers (1)

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

When you use app.user in your template or $this->container->get('security.context')->getToken()->getUser() in your controller, what you get is the User entity. So obviously there's no getCountUnreadAlerts() method for the User entity because you moved it to the repository. So, you've to get the User Repository instead of the Entity to call this method.

So then use $this->getDoctrine()->getRepository('User')->getCountUnreadAlerts() And you may also get another error "getAlertsReceived() does not exist ..." if it's still part of the User Entity.

Upvotes: 1

Related Questions