To give you a clearer understanding on how the user controller class functions, below I've displayed its source code, including the two methods discussed in the previous section. Here's the class: <?php class UsersController { private $model = NULL;
// constructor public function __construct() { // store model object as property $this->model = new Model(MySQL::getInstance(array('host', 'user', 'password', 'database'))); } // 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 echo $view->display(); } // create new user public function create() { // create view object $view = new View('user_form'); // create view properties $view->title = 'Using the MVC design pattern with PHP 5'; $view->heading = 'Create new user'; // display view echo $view->display(); } // update existing user public function update($id) { $this->model->save(array('fname' => 'My first name', 'lname' => 'My last name', 'email' => 'myemail@domain.com'), (int)$id); } } There you have it. Now that this user controller class is becoming more functional, you'll realize how easy it is to build MVC-based web applications using this small framework. Of course, there are some things left that need to be accomplished, such as coding the view files that some methods require. However, there's no need to feel concerned, since they'll be properly tackled in the next part of the series. Final thoughts In this eleventh part of the series, I expanded the initial functionality of the user controller class defined previously by adding a couple of simple methods to it that allow it to create new users in the associated MySQL table. Despite the basic structure of this class, it's handy for demonstrating how easy it is to plug in to different components of the framework, such as the database driver and the input class, as well as the model and the view class. As you saw before, the methods responsible for fetching users and creating new ones use a couple of additional view files that haven't been defined yet. Therefore, in the next tutorial I'm going to code these files. Additionally the controller will be given the ability to delete users. There are many things ahead of us that need to be learned, so don't miss the upcoming part!
blog comments powered by Disqus |
|
|
|
|
|
|
|