<<

ARCHITECTURES

Chapter 3 – : Model-View- Controller

Martin Mugisha

Brief History developed the concept of Model-View-Controllers, like most other concepts. These programmers were gathered at the Learning Research Group (LRG) of Xerox PARC based in Palo Alto, California. This group included , and Red Kaehler among others. C language which was developed at Bell Labs was already out there and thus they were a few design standards in place[ 1] . The arrival of Smalltalk would however change all these standards and set the future tone for programming. This language is where the concept of Model-View- Controller first emerged. However, Ted Kaehler is the one most credited for this . He had a paper in 1978 titled ‘A note on DynaBook requirements’. The first name however for it was not MVC but ‘Thing-Model-View-Set’. The aim of the MVC pattern was to mediate the way the user could interact with the software[ 1] . This pattern has been greatly accredited with the later development of modern Graphical User Interfaces(GUI). Without Kaehler, and his MVC, we would have still been using terminal to input our commands.

Introduction Model-View-Controller is an that is used for implementing user interfaces. Software is divided into three inter connected parts. These are the Model, View, and Controller. These inter connection is aimed to separate internal representation of information from the way it is presented to accepted users[ 2] .

fig 1 SOFTWARE ARCHITECTURES

As shown in fig 1, the MVC has three components that interact to show us our unique information.

Component Interaction Below is a detailed description of the interaction of the components in the MVC design pattern: 1. Controller

 A controller aids in changing the particular state of the model.  The controller takes input from the mouse and keyboard inputs from the user and in turn commanding the model and view to change as required.  A controller interprets interactions from the view and translates them into actions to be performed by the model. User interactions range from HTTP POST and GET in Web applications or clicks and menu selections in Standalone applications.  The controller is also responsible for setting the appropriate view to the appropriate user. 2. Model

 A model is an object representing date or even an activity. A table or even some particular plant-floor production machine process.  The model manages the behavior and also the data of the software application domain.  The model accepts requests for information and responds to the set of instructions meant to change that particular state.  The model shows application data and rules that manage access to update this data.  The model shows the state and low-level behavior of the component. It controls the state and all its changes 3. View

 The view is the visual representation of the state of the model.  The view renders the contents of a model through accessing the data and specifying how the data should be presented.  The view controls the graphical and textual output representations of the software application.  A view typically attaches to a model and renders its contents for display. In summary the MVC frame work likes like this: Input- Processing Output ControllerModelView

SOFTWARE ARCHITECTURES

Implementation of an MVC In the section, I will talk about a few implementations of the MVC design pattern and in particular with Web applications. The MVC pattern has become a popular design pattern with large scale web enterprise application[ 2] . Fig 2[ 2] below shows a sample implementation of MVC design patern. The application is broken down into particular functions, tasks or operations each of which is related to the particular user[ 2] . Each fuction refers to a single controller which may refer to one or more controllers and usually just a single view. Each function deals with an HTTP GET and POST request[ 2] .

Fig 2 .

The Model This is a business entity which has all the properties and functions required by a single business entity. It is always a subclass of an abstract super class with properties and functions common to all database tables. The table is responsible for an array of responsibility ranging from data validation, business rules to task specific behavior while SOFTWARE ARCHITECTURES actual generation of Data Manipulation Language (DML) statements is handled in a separate class[ 2] .

The DML This can also be called the and this is the only object in the framework, which has the permission to communicate with the database. This object can only be called by a model component. This helps in isolating the Model from the underlying database and as such eases the applications ability to be switched from one RDBMS to another simply by switching the DML class[ 2] .

The View This an implementation of a series of scripts that are combined with specific output from each database class to produce an XML document in this case. This file will also include data associated with user menus pagination and scrolling. The XML is then transformed into an HTML document by using generic XSL style sheets[ 2] .

The Controller The component is implemented as a series of functions which interact with either one or more models[ 2] . Each controller is a class and you can have an array of them interacting with different models. Each of them often deal with the following:  Handling HTTP POST and GET request.  Instantiates an object for each business entity  It calls methods on those appropriate objects and thus dealing with a number of database occurrences both as input and as output.  It calls the relevant view object. A good way of understanding what all this means is that in a business of selling shoes for example. There are mangers, sales clerks and the owner. Each of this can send particular requests to the model through the controller and get views that show what is in the database but relevant to them. A manger can have administrative privileges where he can see everyone’s work hours, wages and sales. A sales clerk can only see what shoes are available in the store and sale them but can’t see anyone else wage or work hours. The owner can see all of this information and more like when his supplier is expected to bring in more stock and how much he spends on the stock plus his gross and net profile.

Project For a project to do further research into this concept, I chose to create a social media application based on anonymous story telling where stories were tailored for each user based on information the gave us on where they went to school at. I used PHP as the scripting language combined with MySQL database.

Overview on PHP PHP is at the forefront of the Web 2.0 boom. Though it’s a relatively young , just over fifteen years, there are millions of developers and SOFTWARE ARCHITECTURES powers over twenty million websites. Its large open source community and also leading players in the IT market like IBM, Oracle and Microsoft endorse PHP[ 3] . The development of PHP started in 1995 by Rasmus Lerdof[ 3] . He created a personal collection of scripts and transferred them into a package written in C. This package came to be known as Personal Home Page or PHP for short[ 3] . This package was later available as PHP/FI. The FI stood for Form Interpreter. It showed a lot of similarities to Perl but yet was much easier to use[ 3] . Two years later, Lerdof released PHP2.0

Fig 3 By 1997, and had started to rewrite PHP to make the language better suited for ecommerce applications. The worked with Lerdof and changed the meaning of PHP to ‘Hypertext Preprocessor; as it was widely known today. Which resulted into PHP 3.0. By 2000 Suraski and Gutmans had released PHP 4. This feature had simple object oriented and session handling capabilities. At this point, the number of Web applications using PHP had reached 2 million as shown in fig 3[ 3] . The large PHP community at his point in conjunction with Suraski and Gutmans released PHP 5 in 2004[ 3] . This next iteration included a full support for full object orientation, XML integration and the SOAP protocol[ 3] . Below is an example of PHP OOP implementation: class Person {

public $firstName; public $lastName;

public function __construct($firstName, $lastName = ''){ // optional second argument $this->firstName = $firstName; $this->lastName = $lastName; }

SOFTWARE ARCHITECTURES

public function greet() { return 'Hello, my name is ' . $this->firstName . ' ' . $this->lastName . '.'; } public static function staticGreet($firstName, $lastName) { return 'Hello, my name is ' . $firstName . ' ' . $lastName . '.'; } }

$he = new Person('John', 'Smith'); $she = new Person('Sally', 'Davis'); $other = new Person('iAmine'); $he->greet(); // prints "Hello, my name is John Smith." echo '
'; echo $she->greet(); // prints "Hello, my name is Sally Davis." echo '
'; echo $other->greet(); // prints "Hello, my name is iAmine ." echo '
'; echo Person::staticGreet('Jane', 'Doe'); // prints "Hello, my name is Jane Doe."

PHP 5.1 came in late 2005 and introduced an abstraction layer called PDO[ 3] . This eased PHP’s use with various from different vendors[ 3] . By this point, the number of web 2.0 applications with PHP was reaching 20 million as shown if fig 3. PHP today is a fully comprehensive programming language with solid object orientation support. It has often been referred to as a scripting language but it is more of a dynamic programming language. Unlike the traditional C and , PHP doesn’t need to be compiled but rather interpreted at run time. PHP is behind some of today’s most revolutionary and powerful Web applications like Facebook which has a user base of over 800 million and a constant Alexa rank of 2. Other Web apps include Digg, Yahoo and Wordpress Some of whose logos are easily identified as shown in fig 4

Fig 4- Logos of popular apps using PHP

PHP MVC frameworks PHP has had an array of open source and proprietary frameworks developed to handle strict development. Companies like Facebook have developed their own frameworks but never the less; they are many open source frameworks out there that can be used to create your own Enterprise application with accordance to their particular license. Below is a list of today’s most widely used frameworks, their release date and type of license:

SOFTWARE ARCHITECTURES

Table showing Frameworks [ 4]

Current stable Release Project Start date License version date

Agavi 2005-05 1.0.7 2011-12-22 LGPL

Aiki Framework 2009-09 0.9.1 2012-02-23[7] GPLv3

AppFlower 2009-02 1.3 2012-10-09 GPLv3

CakePHP 2005-08 2.4.7[8] 2014-04-05 MIT

Cgiapp 2004-12 1.0 2004-12-01[9] LGPL

2013-07- CodeIgniter 2006-02-28 2.1.4 OSLv3 08[10]

Fat-Free 2009-09 3.1.0 2013-08-19 GPLv3

FuelPHP 2011-08 1.7.1 2013-12-01 MIT

Hazaar MVC 2012-10 1.1 2013-04-19 Apache 2.0

Joomla 2005-08-17 2.5.19 2014-03-06 GPLv2

Kajona 2006 4.2 2013-07-16 LGPLv2

Laravel 2011-06-11 4.1 2013-12-11 MIT

Lithium 2009-10 0.11 2012-10-03 BSD

2014-03- New 2006-01[11] 2.1.2 17[12] BSD, GPLv2, GPLv3[13]

PHPixie 2012-07 2.1 2012-04-24 BSD

PRADO 2004-01 3.2.2[14] 2013-07-20 New BSD[15]

2011-08- 2005-10 0.4.22 MIT 15[16]

Seagull 2003-10 1.0.4 2013-01-04 BSD

SilverStripe 2005-11 3.0.5 2013-02-20 BSD

Symfony 2005-10 2.3.1 2013-06-19 MIT

TYPO3 Flow 2011-10 2.0.0 2013-07-12 LGPLv3

Xyster Framework 2007-09 02 Build 01 2010-10-18 BSD

Yii 2008-01 1.1.14 2013-08-11 New BSD

Zend Framework 2006-03 2.2.5 2013-10-31 New BSD SOFTWARE ARCHITECTURES

The above libraries all have a few characteristics in common. They all provide libraries to access the database session management and promote code reuse. This in turn means that the effort and time put into development is significantly reduced and so are the resources required to develop and maintain the .

Architecture of the framework. The diagram below, Fig 5[ 5] shows the basic PHP framework with a database management based on MVC.

Fig 5

Mode of interaction 1. User sends a request to the controller 2. Controller analyses the request and calls the Model 3. The model does the necessary logic and connects to the database to make these changes in it. 4. The model sends the results to the controller. 5. The controller forwards the data to the view. 6. Results that respond to that particular user are sent to that user.

Components: Explained below is how these components interact with each other:

The model It is the core of the application of the framework and often handles Database connection. Classes in the model are used to manipulate data in the database e.g deleting, inserting and updating information of the particular user[ 5] . SOFTWARE ARCHITECTURES

The View This is the user of the controller. It is the face of the response to users events. Presentation is often in HTML, CSS, JavaScript. Multiple views can exist for a single model[ 5] .

The Controller This component implements the flow of control between the view and the model[ 5] . It as mentioned earlier contains code that handles actions that cause a change on the model.

Codeigniter I used as a framework of choice. This is because it is one of the most widely used frameworks. Ranking at the top in popularity searches for the framework according to trends and also the number of jobs offered for expertise in knowledge about use[ 5] . Fig 6[ 5] below shows the trends in 2012 for how people searched for the most popular frameworks and as expected, Codeigniter came on top.

Fig 6 Codeigniter is also well documented and easy to learn as compared to the ot her top 5. I was able to develop a hello world app fastest in Codeigniter during my selection process. It also has an array of pre-defined libraries like Calendar, e-mail, validation, uniting testing, session etc. These well documented libraries eased my development of the task at hand.

Project Design Codeigniter calls the default controller set in the config file when thee application is initially run. My default controller rendered a view with a login page and a link to register if you don’t have an account.

SOFTWARE ARCHITECTURES

This log in page is simply a and when submitted is sent to the controller meant to handle this information. Below is a snippet of the code used in the controller to handle this the information sent to the ‘Auth’ controller in the you had forgotten your password clicked forgot password . if (!defined('BASEPATH')) exit('No direct script access allowed'); class Auth extends CI_Controller {

function __construct() { parent::__construct();

$this->load->helper(array('form', 'url')); $this->load->library('form_validation'); $this->load->library('auth_lib’);

}

/** * Generate reset code (to change password) and send it to user * * @return void */ function forgot_password() { if ($this->auth_lib->is_logged_in()) { // logged in redirect(''); } elseif ($this->auth_lib->is_logged_in(FALSE)) { // logged in, not activated redirect('/auth/send_again/'); } else { $this->form_validation->set_rules('login', 'Email or login', 'trim|required|xss_clean');

$data['errors'] = array();

if ($this->form_validation->run()) { // validation ok if (!is_null($data = $this->auth_lib->forgot_password( $this->form_validation->set_value('login')))) {

$data['site_name'] = $this->config->item('website_name', ‘auth_lib’);

// Send email with password activation link $this->_send_email('forgot_password', $data['email'], $data);

$this->_show_message($this->lang->line('auth_message_new_password_sent')); } else { $errors = $this->auth_lib->get_error_message(); foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v); } } $this->load->view('auth/forgot_password_form', $data); } } SOFTWARE ARCHITECTURES

In summary, the controller would send you to the forgot_password_form after the from validations finds out there was nothing entered in the form and render the view below:

When “Get a new password is clicked” the form validation will succeed and the controller will send you to the “auth_lib” library which I used to intermediate between this controller and the Model as this Controller will need information from various Models, so to keep the Controller small, I created a library to mediate. This is also an advantage of Codeigniter. Creating your own Libraries is easy.

php'); define('STATUS_ACTIVATED', '1'); define('STATUS_NOT_ACTIVATED', '0'); class Auth_lib { private $error = array();

function __construct() { $this->ci =& get_instance(); $this->ci->load->config(‘auth_lib', TRUE); $this->ci->load->library('session'); $this->ci->load->database(); $this->ci->load->model('auth_model/users'); $this->ci->load->model('auth_model/user_autologin'); //Other models taken out from snippet // Try to autologin $this->autologin(); }

function reset_password($user_id, $new_pass_key, $new_password) { if ((strlen($user_id) > 0) AND (strlen($new_pass_key) > 0) AND (strlen($new_password) > 0)) {

if (!is_null($user = $this->ci->users->get_user_by_id($user_id, TRUE))) { // Hash password using phpass $hasher = new PasswordHash( $this->ci->confi->item('phpass_hash_strength', ‘auth_lib'), $this->ci->config->item('phpass_hash_portable', 'auth_lib')); $hashed_password = $hasher- >HashPassword($new_password); if ($this->ci->users->reset_password( $user_id, $hashed_password, SOFTWARE ARCHITECTURES

$new_pass_key, $this->ci->config->item('forgot_password_expire', ‘auth_lib'))) { // success

// Clear all user's autologins $this->ci->user_autologin->clear($user->id); return array( 'user_id' => $user_id, 'username'=> $user->username, 'email' => $user->email, 'new_password' => $new_password, ); } } } return NULL; }

This function above will need to use two models i.e. “Users” model and the “User_autologin” model. Below I will show you a small snippet of the code used in the Users model to reset the password:

class Users extends CI_Model { private $table_name = 'users'; // user accounts private $profile_table_name = 'user_profiles'; // user profiles

function __construct() { parent::__construct(); $ci =& get_instance(); $this->table_name = $ci->config->item('db_table_prefix', 'auth_lib').$this- >table_name; $this->profile_table_name = $ci->config->item('db_table_prefix', 'auth_lib').$this- >profile_table_name; } function reset_password($user_id, $new_pass, $new_pass_key, $expire_period = 900) { $this->db->set('password', $new_pass); $this->db->set('new_password_key', NULL); $this->db->set('new_password_requested', NULL); $this->db->where('id', $user_id); $this->db->where('new_password_key', $new_pass_key); $this->db->where('UNIX_TIMESTAMP(new_password_requested) >=', time() $expire_period);

$this->db->update($this->table_name); return $this->db->affected_rows() > 0; }

SOFTWARE ARCHITECTURES

As you can tell above, the model will connect to the database and change the data related to this particular user. Though I did not show code for what the view looked like, you can notice from the little I have shown above how the OOP principles being followed that are the same in the regular programming languages like JAVA. The code is also easy to read and follow. And shows a perfect example of the MVC interaction. My project turned out to be more extensive than I thought as a lot had to be done to maintain strict development standards and security of information. I also used a bunch of other technologies like JQuery libraries and the twitter Bootstrap CSS framework to build a more attractive user interface. I was able to have some substantial progress with a lot of elements of this application developed as the full stack developer. The development time for the deliverables I was able to accomplish could have taken up to three or four times longer if I had not used this framework.

Conclusion By choosing the right software technologies, development of an application can be changed dramatically. The MVC pattern framework is an example of that technology. It eases the development of maintainable code. It also eases labor division as developers can be split into User Interface developers and application logic. Extending and reusing applications written in the MVC pattern is easy e.g. A single model can be used by multiple controllers and also a single controller can use multiple models. All in all, MVC frameworks reduce development time, promote code re-use and ease specialization of developers. This in turn maximizes the potential results obtained from the developers making it a revolutionary concept.

References [1] "PHP MVC Tutorial: Understanding the Model-View-Controller." Udemy Blog. N.p., n.. Web. 29 Apr. 2014. . [2] "The Model-View-Controller (MVC) Design Pattern for PHP." The Model-View- Controller (MVC) Design Pattern for PHP. N.p., n.d. Web. 29 Apr. 2014. [3] "An overview of php." .org. N.p., n.d. Web. 29 Apr. 2014. . [4] "Comparison of web application frameworks." Wikipedia. Wikimedia Foundation, 29 Apr. 2014. Web. 29 Apr. 2014. . [5] "PHP FRAMEWORK FOR DATABASE MANAGEMENT BASED ON MVC PATTERN ." http://airccse.org/. N.p., n.d. Web. 29 Apr. 2014.