Just in case you haven't read the previous part of this series, where I showed the partial definition of a controller class able to fetch, create and update user-related records by using some components of the example framework, in the lines to come I reintroduced the controller’s source code. This way you can study it closely to see how it works. Here’s the file containing the aforementioned controller class: (UsersController.php) <?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); } } The logic implemented by the above user controller class is so easy to follow that’s possible to understand how it works by taking a quick look at the methods that it declares. In short, these methods are used for fetching all of the user-related records stored in the corresponding MySQL table, as well as creating new users and updating existing ones. Besides, notice how the controller employs the model’s API to perform these operations within the data layer, and uses a couple of view files to render the resulting output on the browser when applicable. Again, I’d like to stress that these files still haven’t been created, so if you try the above code sample, you’ll get an ugly complaint from the PHP engine. At this point, the controller class is almost capable of executing CRUD operations against the target “users” MySQL table, since it lacks a method that saves and deletes database records. Therefore, in the section to come I’m going to add to this class the methods we need. To learn more about this process, click on the link that appears below and read the following lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|