21.10.2015 Views

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 />

17<br />

return new Response('Created product id '.$product->getId());<br />

18<br />

}<br />

If you're following along with this example, you'll need to create a route that points to this action<br />

to see it in work.<br />

Let's walk through this example:<br />

lines 8-11 In this section, you instantiate and work with the $product object like any<br />

other, normal PHP object;<br />

line 13 This line fetches Doctrine's entity manager object, which is responsible for<br />

handling the process of persisting and fetching objects to and from the database;<br />

line 14 The persist() method tells Doctrine to "manage" the $product object. This does<br />

not actually cause a query to be made to the database (yet).<br />

line 15 When the flush() method is called, Doctrine looks through all of the objects that<br />

it's managing to see if they need to be persisted to the database. In this example,<br />

the $productobject has not been persisted yet, so the entity manager executes<br />

an INSERT query and a row is created in the product table.<br />

In fact, since Doctrine is aware of all your managed entities, when you call theflush() method, it<br />

calculates an overall changeset and executes the most efficient query/queries possible. For<br />

example, if you persist a total of 100 Product objects and then subsequently call flush(),<br />

Doctrine will create a single prepared statement and re-use it for each insert. This pattern is<br />

called Unit of Work, and it's used because it's fast and efficient.<br />

When creating or updating objects, the workflow is always the same. In the next section, you'll<br />

see how Doctrine is smart enough to automatically issue an UPDATE query if the record<br />

already exists in the database.<br />

Doctrine provides a library that allows you to programmatically load testing data into your<br />

project (i.e. "fixture data"). For information, see DoctrineFixturesBundle.<br />

Fetching Objects from the Database<br />

Fetching an object back out of the database is even easier. For example, suppose you've<br />

configured a route to display a specific Product based on its id value:<br />

public function showAction($id)<br />

{<br />

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

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

->find($id);<br />

if (!$product) {<br />

}<br />

throw $this->createNotFoundException('No product found for id '.$id);<br />

}<br />

// do something, like pass the $product object into a template<br />

88

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

Saved successfully!

Ooh no, something went wrong!