To expand the functionality of the user controller class defined in the previous segment, I'm going to implement its "index()" method. As you'll recall, this is the one called by default for all the controllers of the framework. This method will be tasked with fetching all the users stored in the corresponding MySQL table by using the model's API. Finally, the collected data will be embedded into a specific view file, thus completing the cycle followed by a typical MVC layer.
Having outlined how the "index()" method is going to work, here is its implementation:
// 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 I explained before, the method first creates a new view object that includes a view file called "users.php." It then assigns some properties to the object, including the list of user-related records fetched via the model, and finally renders the view on screen.
Even though it is simplistic, this method does show in a nutshell how to put some of the classes that comprise the framework to work together under the MVC umbrella.
Finally, assuming that the whole framework resides in a folder named "mvc" on the local web server (of course you can name it anything you want), if you wish to call the above index method, then you should type the following in your browser's address bar:
That URL looks pretty nice and SEO-friendly, right? Don't try to access it for the moment, however. The view file hasn't been created yet, so you'll get an ugly error from the PHP engine. You've been warned!
Now that you have a clearer idea of how to partially build a controller class by using this sample framework, it's time to list the class's source code, including the definition of the above "index()" method.
This will be done in the following section. You may want to visit that segment by clicking on the link that appears below.
blog comments powered by Disqus