1-33
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Symfony2 – Franz Jordán 2011<br />
To do this, add the name of the repository class to your mapping definition.<br />
// src/Acme/StoreBundle/Entity/Product.php<br />
namespace Acme\StoreBundle\Entity;<br />
use Doctrine\ORM\Mapping as ORM;<br />
/**<br />
* @ORM\Entity(repositoryClass="Acme\StoreBundle\Repository\ProductRepository")<br />
*/<br />
class Product<br />
{<br />
//...<br />
}<br />
Doctrine can generate the repository class for you by running the same command used earlier to<br />
generate the missing getter and setter methods:<br />
php app/console doctrine:generate:entities Acme<br />
Next, add a new method - findAllOrderedByName() - to the newly generated repository<br />
class. This method will query for all of the Product entities, ordered alphabetically.<br />
// src/Acme/StoreBundle/Repository/ProductRepository.php<br />
namespace Acme\StoreBundle\Repository;<br />
use Doctrine\ORM\EntityRepository;<br />
class ProductRepository extends EntityRepository<br />
{<br />
public function findAllOrderedByName()<br />
{<br />
return $this->getEntityManager()<br />
->createQuery('SELECT p FROM AcmeStoreBundle:Product p ORDER BY p.name ASC')<br />
->getResult();<br />
}<br />
}<br />
The entity manager can be accessed via $this->getEntityManager() from inside the repository.<br />
You can use this new method just like the default finder methods of the repository:<br />
$em = $this->getDoctrine()->getEntityManager();<br />
$products = $em->getRepository('AcmeStoreBundle:Product')<br />
->findAllOrderedByName();<br />
When using a custom repository class, you still have access to the default finder methods such<br />
as find() and findAll().<br />
Entity Relationships/Associations<br />
Suppose that the products in your application all belong to exactly one "category". In this case,<br />
you'll need a Category object and a way to relate a Product object to a Category object. Start<br />
by creating the Category entity. Since you know that you'll eventually need to persist the class<br />
through Doctrine, you can let Doctrine create the class for you.<br />
93