21.10.2015 Views

1-33

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Symfony2 – Franz Jordán 2011<br />

When you query for a particular type of object, you always use what's known as its "repository".<br />

You can think of a repository as a PHP class whose only job is to help you fetch entities of a<br />

certain class. You can access the repository object for an entity class via:<br />

$repository = $this->getDoctrine()<br />

->getRepository('AcmeStoreBundle:Product');<br />

The AcmeStoreBundle:Product string is a shortcut you can use anywhere in Doctrine instead<br />

of the full class name of the entity (i.e.Acme\StoreBundle\Entity\Product). As long as your<br />

entity lives under the Entitynamespace of your bundle, this will work.<br />

Once you have your repository, you have access to all sorts of helpful methods:<br />

// query by the primary key (usually "id")<br />

$product = $repository->find($id);<br />

// dynamic method names to find based on a column value<br />

$product = $repository->findOneById($id);<br />

$product = $repository->findOneByName('foo');<br />

// find *all* products<br />

$products = $repository->findAll();<br />

// find a group of products based on an arbitrary column value<br />

$products = $repository->findByPrice(19.99);<br />

Of course, you can also issue complex queries, which you'll learn more about in theQuerying for<br />

Objects section.<br />

You can also take advantage of the useful findBy and findOneBy methods to easily fetch<br />

objects based on multiple conditions:<br />

// query for one product matching be name and price<br />

$product = $repository->findOneBy(array('name' => 'foo', 'price' => 19.99));<br />

// query for all products matching the name, ordered by price<br />

$product = $repository->findBy(<br />

array('name' => 'foo'),<br />

array('price' => 'ASC')<br />

);<br />

When you render any page, you can see how many queries were made in the bottom right corner<br />

of the web debug toolbar.<br />

89

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!