Object-Oriented PHP5 Data Mapper ORM

The base finder methods for PHP DataMapper are get, all, and first.

get()

The get function is used to get a single row by primary key:

1
2
# Post with a primary key of 1
$post = $postMapper->get(1);

It can also be used to return a new empty row object when used with no parameters:

1
2
3
4
5
6
7
8
9
10
11
12
# New, empty post row object
$post = $postMapper->get();
 
# Set data and save it
$post->title = "Test Post #1";
$post->body = "
 
This is my test post!
 
";
$post->status = "draft";
$postMapper->save($post);

all()

The all function is the primary finder method. It can be used in a number of ways, with or without conditions, to find the rows you need:

1
2
3
4
5
6
7
8
9
10
11
# All posts
$posts = $postMapper->all();
 
# All posts with a 'published' status
$posts = $postMapper->all(array('status' => 'published'));
 
# All posts created before today
$posts = $postMapper->all(array('date_created <' => date($postMapper->getDateFormat())));
 
# Posts with 'id' of 1, 2, 5, 12, or 15 - Array value = automatic "IN" clause
$posts = $postMapper->all(array('id' => array(1, 2, 5, 12, 15)));

The returned result will always be an instance of phpDataMapper_Model_ResultSet, which is a traversable collection of row objects (phpDataMapper_Model_Row by default). If there are no results for the issued query, an empty result set will be returned. The ResultSet collection object implements SPL Iterator and Countable, so it acts exactly like an array and can be used in foreach() and while() loops and can also be used in PHP’s count() function.

first()

The first function works exactly like the all method, with all the same parameters. The difference, of course, is that it returns the first found row object instead of a collection of all matched row objects. This can be useful when you only need a single row, and want to work with the row immediately.

1
2
# First posts with a 'published' status
$post = $postMapper->first(array('status' => 'published'));

Immune to SQL Injection

Your data is safe. All of the finders and query methods in PHP DataMapper use native prepared statements with bound parameters for the highest level of security possible. Rest assured that every value that gets passed in is safe, no matter the contents.