Before I begin adding to the user controller class the extra methods which will let it perform record inserts and updates, I'm going to show this class's partial definition, so you can see how it was built initially.
The file containing the definition of the controller was called "UsersController.php" and was created like this:
private $model = NULL;
public function __construct()
// store model object as property
$this->model = new Model(MySQL::getInstance(array('host', 'user', 'password', 'test')));
// fetch and display all users
public function index()
// create view object
$view = new View('users');
// create view properties
$view->title = 'Using the MVC design pattern with PHP 5';
$view->heading = 'User List';
$view->users = $this->model->fetchAll();
// display view
As seen above, for the time being the controller only gives a concrete implementation to its constructor and to its "index()" method, hence its limited functionality. In this specific case, the constructor grabs an instance of the associated model and stores it as a class property. On the other hand, the "index()" method first creates a new view object and assigns to it some properties, then retrieves all of the users stored on the corresponding MySQL table, and finally renders the view on the browser.
Even though I clarified this point in the previous tutorial, I'll do it again here: as you can see, the file taken by the view object hasn't been defined yet. So assuming that the framework's source files reside in a folder called "mvc," if you type into your browser's address bar a URL like the following:
You'll get an error from the PHP engine for the reason given before. To avoid this ugly error message, I suggest that you not test the controller until all of the view files have been properly created. Keep that warning in mind!
At this point, the functionality of the user controller class is reduced to fetching all of the rows contained in the "users" MySQL table, so it's time to add more methods to it.
In consonance with the concepts deployed in the introduction, in the section to come I'm going to incorporate into the controller a couple of additional methods that will be used for inserting and updating records in the table.
To learn more about how these methods will be defined, click on the link below and read the following segment.
blog comments powered by Disqus