As I promised in the segment that you just read, below I listed the full source code corresponding to the previous "UserMapper" class, this time including the "delete()" method discussed a moment ago: (UserMapper.php)
<?php
class UserMapper extends DataMapperAbstract { protected $_table = 'users';
// fetch domain object by ID public function find($id) { // if the requested domain object exists in the identity map, get it from the map if (array_key_exists($id, $this->_identityMap)) { return $this->_identityMap[$id]; } // if not, get domain object from the database $this->_db->query("SELECT * FROM $this->_table WHERE id = $id"); if ($row = $this->_db->fetch()) { $user = new User; $user->id = $row->id; $user->fname = $row->fname; $user->lname = $row->lname; $user->email = $row->email; // save domain object to the identity map $this->_identityMap[$id] = $user; return $user; } }
// save domain object public function save(DomainObjectAbstract $user) { // update domain object if ($user->id !== NULL) { $this->_db->query("UPDATE $this->_table SET fname = '$user->fname', lname = '$user->lname', email = '$user->email' WHERE id = $user->id"); } // insert domain object else { $this->_db->query("INSERT INTO $this->_table (id, fname, lname, email) VALUES (NULL, '$user->fname', '$user->lname', '$user->email')"); } }
// delete domain object public function delete(DomainObjectAbstract $user) { if ($user->id !== NULL) { $this->_db->query("DELETE FROM $this->_table WHERE id = $user->id"); } } } Mission accomplished. Now, the user mapper encapsulates enough functionality to perform CRUD operations on its associated MySQL table via a fancy interface. Besides, it's valid to stress again that it implements an identity map, a feature that makes it even more efficient when mapping domain objects to the database and vice versa. Finally, feel free to edit and improve all of the code samples shown in this tutorial. Doing this will surely expand your current background in building data mapper classes in PHP. Final thoughts In this penultimate installment of the series, I demonstrated how to provide the previous "UserMapper" class with the ability to delete users from its associated MySQL table, certainly a process that didn't raise any unexpected problems. Now that the mapper is capable is performing full CRUD operations, the next logical step is to develop an example that shows how to use it with some user domain objects. Precisely that educational exercise will be covered in depth in the last part of the series, so here's my final piece of advice: don't miss the final tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|