Download The Code
PHP Source on GitHub:
http://github.com/vlucas/phpDataMapper/
You can check out the “bleeding edge” code using Git:
git clone git://github.com/vlucas/phpDataMapper.git
How do I use This Thing?
Head over to the Finders page to find out how to get started using your mapper.
Require it in Your Application
<?php // Require base mapper require 'phpDataMapper/Base.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 “Mysql” adapter is used.
<?php // Setup database connection require 'phpDataMapper/Adapter/Mysql.php'; try { $adapter = new phpDataMapper_Adapter_Mysql('localhost', 'db', 'root', ''); } catch(Exception $e) { echo $e->getMessage(); exit(); }
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.
<?php // Post class PostMapper extends phpDataMapper_Base { // Specify the data source (table for SQL adapters) protected $_datasource = "blog_posts"; // Define your fields as public class properties public $id = array('type' => 'int', 'primary' => true, 'serial' => true); public $title = array('type' => 'string', 'required' => true); public $body = array('type' => 'text', 'required' => true); public $status = array('type' => 'string', 'default' => 'draft'); public $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!
<?php $postMapper = new PostMapper($adapter);
Get Your Tables Up to Date
Automatically create or sync your table structure with the defined fields in the mapper. No *.sql or text files need to be included with the distribution of your project.
<?php $postMapper->migrate();