In the prior section, I showed you the partial definition of the model class, which is responsible for performing CRUD operations against a selected MySQL table. Nevertheless, the development of this class is still incomplete, since it’s necessary to add a method that deletes database rows; that is the “D” letter within the CRUD acronym. Below I listed the full source code of the file that contains the model class, this time including the missing method. Take a look at this file: (Model.php) <?php class Model { private $db = NULL; private $table = 'users'; // constructor public function __construct(MySQL $db, $table = '') { $this->db = $db; if ($table !== '') { $this->table = $table; } } // get all rows from the specified table public function fetchAll() { $rows = array(); $this->db->query('SELECT * FROM ' . $this->table); while ($row = $this->db->fetch()) { $rows[] = $row; } return $rows; } // update/insert row public function save(array $data, $id = NULL) { if (!empty($data)) { foreach ($data as $field => $value) { $value = mysql_escape_string($value); if (!is_numeric($value)) { $data[$field] = ''' . $value . '''; } } if ($id !== NULL) { $set = ''; foreach($data as $field => $value) { $set .= $field .'=' . $value . ','; } $set = substr($set, 0, -1); $this->db->query('UPDATE ' . $this->table . ' SET ' . $set . ' WHERE id=' . (int)$id); } else { $fields = implode(',', array_keys($data)); $values = implode(',', array_values($data)); $this->db->query('INSERT INTO ' . $this->table . ' (' . $fields . ')' . ' VALUES (' . $values . ')'); } } }
// delete row public function delete($id = NULL) { if ($id !== NULL) { $this->db->query('DELETE FROM ' . $this->table . ' WHERE id=' . (int)$id); } } }// End Model class Done. With the incorporation of the brand new “delete()” method, the model can perform true CRUD operations on a selected MySQL table. With this addition, the framework is also capable of handling the data layer through a compact API. At this point, do you realize how the MVC structure which this framework relies on is starting to take shape? I bet you do. Even so, the best way to understand how to use the framework is by way of a concrete example that puts all of its building blocks to work together. This process will be tackled in the upcoming part. Final thoughts In this ninth episode of the series, I added to the framework an extensible model class, which as you saw, can be used for running CRUD operations against a selected MySQL database table. In the next part, things will become even more interesting. I’m going to start developing a basic database-driven application by using the set of classes developed so far, which naturally will require coding a controller class as well. Don’t miss the forthcoming tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|