The base finder methods for phpDataMapper are get, all, and first.
get([$pimaryKey])
The get function is used to get a single entity by primary key:
Note that you can't chain other function calls off the first method like you can the all method, because an entity object is immediately returned if found instead of a query object. Boolean false is returned if no entity matches your search criteria.
<?php # Post with a primary key of 1 $post = $postMapper->get(1); It can also be used to return a new empty entity object when used with no parameters: <?php # New, empty post entity $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([array $conditions])
The all function is the primary finder method. It can be used in a number of ways, with or without conditions, to find the entities you need:
<?php # All posts $posts = $postMapper->all(); # All posts with a 'published' status, descending by date_created $posts = $postMapper->all(array('status' => 'published'))->order(array('date_created' => 'DESC')); # All posts created before today $posts = $postMapper->all(array('date_created <' => date($postMapper->adapter()->dateFormat()))); # 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)));
phpDataMapper delays query execution to the last possible second, which means the returned result ($post) will be an instance of phpDataMapper_Query until is is put in a foreach() loop or count() function. When executed, an instance of phpDataMapper_Collection will be returned, which is a traversable collection of entities (phpDataMapper_Entity by default). If there are no results for the issued query, an empty result set will be returned. The 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. The query can be executed early and the result set can be returned immediately by calling $posts->execute().
first[(array $conditions])
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 entity instead of a collection of all matched entities. This can be useful when you only need a single entity object, and want to work with the entity immediately.
<?php # 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 phpDataMapper 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.