Doctrine: Object Relational Mapping for Your PHP Development, Page 2
Querying the Database
The third piece of this introductory puzzle involves querying the database from within the application. Doctrine is an object-relational mapper, meaning it facilitates the often tedious and difficult translation of a database's table structures into PHP objects, which can easily be manipulated from within the application. Because Doctrine generates the models that form this bridge for you, all you need to do is take advantage of Doctrine's special object-oriented syntax to query the database. Open the
index.php file located in the
sandbox directory and modify it so it looks like this:
<?php require_once('config.php'); $models = Doctrine_Core::loadModels('models'); $userTable = Doctrine_Core::getTable('User'); $user = $userTable->findByEmail('email@example.com'); echo $user->first_name;
This example uses one of Doctrine's magic methods to query the database for the user identified by the e-mail address
firstname.lastname@example.org, creating an array of objects containing any records that match this criteria. The example subsequently references the returned record's
first_name attribute, which returns the name
The Future of Doctrine
With Doctrine 2 barreling towards an autumn release, and popular frameworks such as the Zend Framework working towards adoption in a future release, Doctrine's future as the de facto ORM solution for the PHP community is indeed bright.
- The Doctrine 1.2 manual: You should start here if you'd like to immediately begin integrating Doctrine into a project headed for production. Alternatively, you can purchase the documentation in print format at Amazon.com
- Doctrine 2 documentation: Although still months from an official release, Doctrine 2 is already very well documented. Check out this link to learn more about the fantastic features the forthcoming version has to offer.
Doctrine is such a powerful solution that this tutorial serves as little more than a taste of what's possible. Even so, the material presented here is indicative of Doctrine's ability to positively impact almost every aspect of your interaction with the project database. As always, we'd love to hear about what other database-oriented tools you're using to simplify your programming life! Tell us about them in the comments.
About the Author
Jason Gilmore is the founder of EasyPHPWebsites.com. He also is the author of several popular books, including "Easy PHP Websites with the Zend Framework," "Easy PayPal with PHP," and "Beginning PHP and MySQL, Third Edition."