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

a new property with mapping metadata to Product and run this task again, it will generate the<br />

"alter table" statement needed to add that new column to the existing products table.<br />

An even better way to take advantage of this functionality is via migrations, which allow you to<br />

generate these SQL statements and store them in migration classes that can be run<br />

systematically on your production server in order to track and migrate your database schema<br />

safely and reliably.<br />

Your database now has a fully-functional product table with columns that match the metadata<br />

you've specified.<br />

Persisting Objects to the Database<br />

Now that you have a mapped Product entity and corresponding product table, you're ready to<br />

persist data to the database. From inside a controller, this is pretty easy. Add the following<br />

method to the DefaultController of the bundle:<br />

1<br />

2<br />

3<br />

4<br />

// src/Acme/StoreBundle/Controller/DefaultController.php<br />

use Acme\StoreBundle\Entity\Product;<br />

use Symfony\Component\HttpFoundation\Response;<br />

// ...<br />

5<br />

6<br />

7<br />

8<br />

9<br />

10<br />

11<br />

public function createAction()<br />

{<br />

$product = new Product();<br />

$product->setName('A Foo Bar');<br />

$product->setPrice('19.99');<br />

$product->setDescription('Lorem ipsum dolor');<br />

12<br />

13<br />

14<br />

15<br />

$em = $this->getDoctrine()->getEntityManager();<br />

$em->persist($product);<br />

$em->flush();<br />

16<br />

87

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

Saved successfully!

Ooh no, something went wrong!