Download The Code
>> Pre-Release package at revision 44 (phpDataMapper-pre-r44.zip)
PHP Source on Google Code:
http://code.google.com/p/phpdatamapper/
You can check out the “bleeding edge” code using SVN:
1 | svn checkout http://phpdatamapper.googlecode.com/svn/trunk/PHPDataMapper phpDataMapper |
Require It In Your Application
1 2 | // DataMapper base model require 'phpDataMapper/Model.php'; |
Setup Your Database Connection
Your database connection should be established before using your model, because the database adapter you choose to use will be passed as the first parameter in the constructor when instantiating your model classes. In this example, the “Pdo_Mysql” adapter is used.
1 2 3 4 5 6 7 8 | // Setup database connection require 'phpDataMapper/Database/Adapter/Pdo/Mysql.php'; try { $adapter = new phpDataMapper_Database_Adapter_Pdo_Mysql('localhost', 'database_name', 'root', 'password'); } catch(Exception $e) { echo $e->getMessage(); exit(); } |
You can establish as many different database connections as you need, and pass them into any instance of phpDataMapper you want. This makes it very easy to use multiple database connections in different models.
Define Your Model
Since your model classes drive your database, you will need to define the table name and all the fields in each model. This may seem tedious at first if you’re used to setting up the database tables first through another GUI like phpMyAdmin or MySQL Administrator, but it helps with migrations and table syncing operations down the road, and ensures your model always knows the available fields for building error-free queries and performing data validation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // Post class PostMapper extends phpDataMapper_Model { // Specify the database table protected $table = "blog_posts"; // Define your fields protected $fields = array( 'id' => array('type' => 'int', 'primary' => true), 'title' => array('type' => 'string', 'required' => true), 'body' => array('type' => 'text', 'required' => true), 'status' => array('type' => 'string', 'default' => 'draft'), 'date_created' => array('type' => 'datetime') ); } |
Instantiate The Mapper
Create a new instance of your mapper to use in your code. Don’t forget to pass in your database connection!
1 | $postMapper = new PostMapper($adapter); |
How do I use This Thing?
Head over to the Finders page to find out how to get started using your mapper.