I am working on a data mapper project too and my first thought was an Active Record like implementation.
But fetching 200 data records and build an instance for each of these records is really slow. Besides why i have to make an instance object when i only want is to print the fields of the record to a view?
It is usefull to make an instance of object in CRUD proccess like Active Record Pattern does. But when reading data, i think it is better to use stdClass objects with pair of key/values.
For example.
We have User model which represent a table in our database:
we have a Finder class so we can call our find methods:
I use get_called_class() on PHP5.2 from here
http://www.php.net/manual/en/function.g ... .php#93799
Code: Select all
class Finder {
public static function find(){
$class = get_called_class();
$query = new Query($class);
return $query;
}
}
we have a Query so we can build queries:
Code: Select all
class Query extends Mysql {
public function select($args){}
public function where ($conditions){}
/*
* more function to create queries
*/
public function fetch_one(){
//Creates a collection object from data fetched from database and return
}
public function fetch_all(){
//Creates a collection object from data fetched from database and return
}
}
Mysql class is an adapter for mysql to execute queries build by Query class.
last we make a Collection class to iterate through results
Code: Select all
class Collection implements Iterator, Countable, ArrayAccess {
protected $results = array();
public function __construct($results ) {
$this->results = $results;
}
}
So we this is how it works:
Code: Select all
$users = User::find()->where('country_id = 10')->fetch_all();
Now $users is a collection object with data from all users from country with id = 10
We can use $users to iterate through results, use foreach() etc.
The key point is to create a very good Query class so you can build queries with associations etc.
Code: Select all
$users = User::find()->includes("country")->where('country_id = 10')->fetch_all();
The above will make a query for $user with country_id = 10, and a query from country table("SELECT * FROM countries WHERE id = 10")
Then will make a nested object like this ( well it will be more complex cause we have Collection call objects not stdClass object but i make it like this for better understanding)
Code: Select all
[User] => stdClass Object
(
[1] => Array
(
[id] => 1
[country_id] => 10
[country] => stdClass Object
(
[id] => 10
[name] => "Some Country Name"
)
)
[2] => Array
(
[id] => 2
[country_id] => 10
[country] => stdClass Object
(
[id] => 10
[name] => "Some Country Name"
)
)
)
and we can call $user[0]->country->name to get country name.
What do you think?