Home arrow PHP arrow Page 3 - Creating a Model Class for an MVC-based Framework

Managing the database layer with a basic model class - PHP

In this ninth part of the series, I add an extensible model class to the framework. This class can be used for running CRUD operations against a selected MySQL database table.

TABLE OF CONTENTS:
  1. Creating a Model Class for an MVC-based Framework
  2. Review: the View class
  3. Managing the database layer with a basic model class
  4. Deleting database records with a final model class method
By: Alejandro Gervasio
Rating: starstarstarstarstar / 3
June 28, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

As I just mentioned in the preceding section, one of the core components that must be added to this MVC-based framework is a model that permits it to handle the corresponding data layer in an independent way. Since this layer will be composed of one or multiple MySQL database tables, the model will perform CRUD operations by using the MySQL driver developed in a previous tutorial.

Although a full-featured model should be abstract enough for handling all sorts of persistent storage mechanisms, and not just database tables, the one that I’m going to build next will use only the MySQL server. This is certainly good enough for demonstration purposes.

Having clarified that point, please look at the initial definition of the new model class, which is as follows:

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 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 . ')');

}

}

}

From the previous code sample, it’s easy to see that the “Model” class implements a bunch of basic methods for selecting, inserting and updating records in a specified MySQL table. Please notice the injection of an instance of the MySQL driver via the class’ constructor, which allows you to expand the model to support additional database drivers.

Also, you should note that the model will work with a default “users” MySQL table, but naturally it’s possible to use a different table in accordance with your specific needs.

So far, so good. At this stage, the “Model” class can perform database selects, inserts and updates as well. Now you're wondering where the method that deletes records is, right? Well, it hasn’t been coded yet, but this will be fixed quickly.

In the final section of this tutorial, I’m going to define the remaining method, thus finishing the construction of the model class.

Go ahead and read the following segment. We’re almost done with the model!



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: