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 />
Databases and Doctrine ("The<br />
Model")<br />
Let's face it, one of the most common and challenging tasks for any application involves<br />
persisting and reading information to and from a database. Fortunately, Symfony comes<br />
integrated withDoctrine, a library whose sole goal is to give you powerful tools to make this<br />
easy. In this chapter, you'll learn the basic philosophy behind Doctrine and see how easy working<br />
with a database can be.<br />
Doctrine is totally decoupled from Symfony and using it is optional. This chapter is all about the<br />
Doctrine ORM, which aims to let you map objects to a relational database (such<br />
as MySQL, PostgreSQL or Microsoft SQL). If you prefer to use raw database queries, this is easy,<br />
and explained in the "How to use Doctrine's DBAL Layer" cookbook entry.<br />
You can also persist data to MongoDB using Doctrine ODM library. For more information, read<br />
the "DoctrineMongoDBBundle" documentation.<br />
A Simple Example: A Product<br />
The easiest way to understand how Doctrine works is to see it in action. In this section, you'll<br />
configure your database, create a Product object, persist it to the database and fetch it back<br />
out.<br />
Code along with the example<br />
If you want to follow along with the example in this chapter, create anAcmeStoreBundle via:<br />
php app/console generate:bundle --namespace=Acme/StoreBundle<br />
Configuring the Database<br />
Before you really begin, you'll need to configure your database connection information. By<br />
convention, this information is usually configured in an app/config/parameters.ini file:<br />
;app/config/parameters.ini<br />
[parameters]<br />
database_driver = pdo_mysql<br />
database_host = localhost<br />
database_name = test_project<br />
database_user = root<br />
database_password = password<br />
Defining the configuration via parameters.ini is just a convention. The parameters defined in<br />
that file are referenced by the main configuration file when setting up Doctrine:<br />
doctrine:<br />
dbal:<br />
driver: %database_driver%<br />
host: %database_host%<br />
dbname: %database_name%<br />
user: %database_user%<br />
password: %database_password%<br />
By separating the database information into a separate file, you can easily keep different version<br />
of the file on each server. You can also easily store database configuration (or any sensitive<br />
information) outside of your project, like inside your Apache configuration, for example. For<br />
more information, see How to Set External Parameters in the Service Container.<br />
83