Adding More Methods to the Controller Class of an MVC-Based Framework

In this eleventh part of the series, I expand the initial functionality of the user controller class defined previously by adding two simple methods to it. These allow it to create new users in the associated MySQL table.

If you’re a PHP coder who wants to learn how to use the Model-View-Controller design pattern to develop an extensible framework in a few simple steps, then you’ve come to the right place. This series of articles guides you through the construction of a stack of reusable components, which can be put to work together easily under the schema imposed by this architectural pattern.

And now that you’ve been introduced to the goal of this series, it’s time to review the topics that were discussed in the last tutorial. In that part of the series I started building a basic MySQL-driven application, which used some of the classes that comprise this sample framework to fetch data from a table that stored some user-related records.

The class that performed this retrieval process was a simple controller, which used the functionality of its associated model for accessing the referenced MySQL table. However, it must be said that this controller class in its current state is very limited, since it currently can use only its "index()" method to fetch the aforementioned database records.

So, what’s the next step that must be taken toward making the controller a bit more functional? Well, since its model already has the required logic to perform CRUD operations against the selected table, in the next few lines I’m going to add to the controller a couple of methods that will allow it to insert and update database rows in a simple fashion.

Now, it’s time to get rid of the preliminaries and continue demonstrating with some functional code samples how to use this MVC-based framework for developing a simple database-driven web application. Let’s get going!

{mospagebreak title=Review: the initial definition of the user controller class}

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:

<?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’, ‘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

echo $view->display();

}

}

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:

http://localhost/mvc/users  

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.

{mospagebreak title=Creating new users and updating existing ones}

As I said in the segment that you just read, to make the previous user controller class more functional, it’s desirable to enable it to create new users and update existing ones. To do so, I’m going to append to the controller a couple of extra methods, which will use the API of the model to perform the aforementioned tasks.

Below I listed the signatures of these brand new methods, so look at them, please:

// 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);

}

Understanding how these methods work is pretty straightforward. In the first case, the "create()" method is the most interesting. It uses a view object to render an HTML form, which will be used for collecting data about a new user. This logically implies that there must be another method that actually saves this information to the database, but this topic will be covered in more detail in the next tutorial.

On the other hand, as its name suggests, "update()" will simply update an existing user based on its ID, which must be passed as part of the user request. It’s that simple, really.

After adding the previous methods, the user controller definitively looks much more useful, bur the most important thing to note here is the way that it reuses some of the classes of the framework under the schema of the MVC design pattern.

Now that you’ve grasped the underlying logic of the controller, it’s time to show its full source code, including the couple of methods that you just learned. This will be done in the last section of this tutorial, so to get there simply click on the link below and keep reading.

{mospagebreak title=The full definition of the controller class}

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!

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye