HTML and CSS Reference
In-Depth Information
Adding a Method to the Model Class
The last step in the form-handling chain is to add a model method. But first, we need a model class.
Fortunately, this app will keep things simple, so the model classes simply extend the Model class, which gives
them access to the PDO-powered database connection, and then declare the required methods. No additional setup
is required.
Continuing with our Example class, we need to create the Example_Model class that was instantiated earlier.
The only method this class needs is the update_foo_count() method called by the action handler method, and the
method simply needs to increment the count of “foos” that have occurred and return an array of data.
Here's what that would look like:
class Example_Model extends Model
public function vote_question( $room_id, $sayer_id )
// Increments the vote count for the question
$sql = "UPDATE sayings
SET foo_count = foo_count+1
WHERE sayer_id = :sayer_id";
$stmt = self::$db->prepare($sql);
$stmt->bindParam(':sayer_id', $sayer_id, PDO::PARAM_INT);
return array(
'room_id' => $room_id,
'sayer_id' => $sayer_id,
This is the basic pattern of all the models that will be built in this app. This method creates an SQL statement,
prepares it using PDO, and then performs whatever database manipulation is required (an UPDATE in this case).
Once the query is executed, an array with relevant data is returned.
the models in this app rely heavily on prepared statements, which are much more secure than standard
SQl queries. You won't need to know much more than what's displayed in the previous example to complete the models
in this topic, but if you need a refresher on pdO, visit the php manual at .
This chapter was a dense one. At this point, you've successfully built a framework for your app based on the
principles of MVC.
However, you've still got a little ways to go before the back end is complete. In the next chapter, you'll build the
controllers, views, and models for the Room and Question data types.
Search WWH ::

Custom Search