In the preceding segment, I showed the definition of the class that will allow you to access MySQL tables in a quite abstract way. So, the next thing we must do toward the development of the MVC-based application is build a model class that will use the MySQL handler for manipulating records related to some fictional users. Below I included the source code of this brand new model class, which has been called, not surprisingly, “UserModel.” Study its definition, please: class UserModel { private $db = NULL;
// constructor public function __construct(MySQL $db) { $this->db = $db; }
// get all users public function getAll() { return $this->db->query("SELECT * FROM users"); }
// get a single user public function get($id = 1) { return $this->db->query("SELECT * FROM users WHERE id = '$id'"); }
// create/update user public function save($data, $id = NULL) { if (is_array($data) && !empty($data)) { if ($id === NULL) { $data = array_values($data); $fields = ''' . implode("','", $data) . '''; $this->db->query("INSERT INTO users (id, fname, lname, email) VALUES (NULL, $fields)"); } else { $fields = ''; foreach ($data as $field => $value) { $fields .= $field . '='' . $value . '','; } $fields = substr($fields, 0, -1); $this->db->query("UPDATE users SET $fields WHERE id=$id"); } } }
// delete user public function delete($id = NULL) { if ($id !== NULL) { $this->db->query("DELETE FROM users WHERE id=$id"); } } } Well, I don’t wan to sound too verbose, but you’ll have to agree with me that the definition of the previous “UserModel” class has some interesting points that deserve a close analysis. First, as one would expect from a decent model, the class implements some simple methods that allow it to perform CRUD operations in a straightforward manner. And last but not least, the model takes an instance of the MySQL handler, which is naturally used by the pertinent methods to execute the CRUD operations against a predefined “users” MySQL table. This example is very illustrative because it shows how to create a model in a few simple steps, and demonstrates how the dependency injection pattern can be implemented with minor hassles within the MVC schema. What else can you ask for? In reality you can ask for much more. It’s quite possible that at this moment you’re wondering how to use the two classes shown before for inserting, updating and deleting users without having to directly write any SQL query. Is that what you’re asking for? In the section to come I’m going to code a simple script that will perform all of those operations in a very simple manner. Naturally, to learn how this script will be built, you’ll have to click on the link below and read the following lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|