Fabian
Fabian

Reputation: 1836

Basic Symfony 2 Object-Entity understanding

I have two entities, event and participant. They have a relation, like every event can have many participants.

participants have properties like checked, visible and so on.

normaly i can do some like $event->getParticipant(); in my controller.

what is now the best way to get more specific selections? for example i want to do implement some of the following functions:

$event->getVisibleParticipant();
$event->getCheckedParticipant();
$event->getVisibleAndCheckedParticipant();

how and where can i implement such functions the best way?

I have tried to implement a EventRepository, but it says that the method i want to call there is undefined...

Upvotes: 0

Views: 78

Answers (1)

Peter Bailey
Peter Bailey

Reputation: 105898

You can probably best accomplish this with Doctrine's filter method for collections

http://api.nellafw.org/class-Doctrine.Common.Collections.ArrayCollection.html

So, on your Event entity, let's assume your relationship looks like this

<?php

namespace /Your/Bundle/Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Table()
 * @ORM\Entity()
 */
class Event
{
  /**
   * @ORM\OneToMany(targetEntity="Participant", mappedBy="event")
   */
  protected $participants;

  public function __construct()
  {
    $this->participants = new ArrayCollection();
  }
}

So all you need to do is add a query method (to the Event entity) that will use the filtering capabilities of Doctrine's collections

/**
 * Retrieves all associated participants that are visible
 *
 * @return \Doctrine\Common\Collections\ArrayCollection
 */
public function getVisibleParticipants()
{
  return $this->participants->filter( function( Participant $participant )
  {
    // Add only visible participants to the returned collection
    return (boolean) $participant->getVisible();
  });
}

Upvotes: 1

Related Questions