Implementing MVC in PHP: The Modelby Joe Stump
This article series (starting with Understanding MVC in PHP and continued in Implementing MVC in PHP: The Controller and Implementing MVC in PHP: The View) demonstrates how to build an MVC web framework using PHP 5. This article explains the Model part of Model-View-Controller design.
The Model is where the majority of the application’s logic sits. It is where you run queries against the database and perform calculations on input. A good example of what a Model would look like is a simple login script. The login script gets user input from a form, validates it against the database, and then logs in the user.
The first application using the newly created framework will be the
users module. I will be creating three Models:
- login.php validates input from a form against the database
- logout.php logs a user out and destroys the associated session
- whoami.php displays simple user information, similar to the Unix program of the same name
Because I am introducing the idea of sessions and users into the framework, I will need to create a few more foundation classes as well as a table in a database. Before I go over the code of login.php, I’d like to walk through these classes.
FR_Session is a wrapper for the built-in PHP sessions. The code isn’t very involved and provides only basic support for starting, destroying, and writing sessions.