Duplicate Transaction
MVC-Design Pattern In Native PHP

MVC Design Pattern with a PHP example

Model-View-Controller is the most widely used design pattern in programming languages such as Java, PHP, C, C++, and C#.
In an object-oriented programming paradigm, MVC relates the user interface to the underlying data model.

In the MVC model, three main components are involved in software development. Each one of these components is oblivious to the works and responsibilities of others.

Model

 The Model is responsible for data access and data manipulation. The Model knows how to handle the data stored in the application. It also knows how to respond to requests for information. The Model also represents the underlying, logical structure of data in an application and the high-level classes associated with it. 

View

The View presents the data (from the Model) to the user. It’s the UI and the component that shows off the information. It is a collection of classes representing the elements in the user interface.

Controller

The Controller is the bridge that connects the Model to the View. It represents the classes connecting the Model and the View. The Controller receives a request from the user (directly or via the View) and puts the Model to work. The Controller receives the requested data in the proper format and forwards it to the View.

MVC Design Pattern

A real-life example

In most larger restaurants, there is a position called expediter.
The expediter is responsible for communicating between the kitchen and with the servers. Expediter ensures timely delivery of the food to the patrons of the restaurant.
In this restaurant, a server is a View; Kitchen is the Model, and expediter is the Controller.

Restaurant Expeditor

In Short

MVC allows you to keep the application’s business logic detached from its interface. MVC also helps you keep all functionalities encapsulated and independent from each other. You can modify each component in total isolation from others and avoid breaking your code.

MVC Implementation in native PHP

Now let see how we can implement an MVC method in PHP. I have designed this part to be easy-to-understand and practical. In the example below, I am not using any PHP framework, and the code is in native PHP. See my article about PHP Frameworks.
The figure below presents the project structure:

Model and Classes

I am going to start with the Model component.
The Model is responsible for the data, and the logic of an application or the business logic.
Model’s responsibilities include; data store, retrieve, delete, and update. Generally, it includes database operations and the implementation of the operations that invoke external web services or APIs.

In this example, the Model includes two classes:
the “Model” class and a “Transaction” class.

The Model class doesn’t need a presentation. The “Transaction” class is an entity(object) class, and I expose this class to the View layer.

In a proper implementation of the MVC pattern, we only expose entity classes(objects) by the Model, and these objects cannot encapsulate any business logic.
Their sole purpose in an entity class is to keep data. Depending on the implementation, an Entity object can be in XML or JSON format.

<?php
include_once("model/Transaction.php");
class Model {
	public function getTransactionList()
	{
		// Sample data
		return array(
			"1" => new Transaction("1","14.95", "VISA", "8564"),
			"2" => new Transaction("2","9.95", "MASTERCARD", "4100"),
			"3" => new Transaction("3","89.95", "AMEX", "8105")
		);
	}
public function getTransaction($id)
	{
	// get all the transactions 
	// usually this will be done in a database with a select command
		$allTransactions = $this->getTransactionList();
		return $allTransactions[$id];
	}

}
?>

Add here is our Transaction object:

<?php
class Transaction {
	public $id;
	public $amount;
	public $cardType;
	public $last4;
	
	public function __construct($id,$amount, $cardType, $last4)  
    {  
	    $this->id = $id;            
        $this->amount = $amount;
	    $this->cardType = $cardType;
	    $this->last4 = $last4;
    } 
}
?>

View

The View (presentation layer)is responsible for formatting the data received from the Model. The data can come in different formats from the Model, including, XML structures, JSON, HTML,…

In our example, the View has two files. One file displays a single transaction, and the second file is to display a list of transactions. The output format is a simple HTML table.

<html>
<head></head>

<body>

<table>
	<tr><td>Id</td><td>Amount</td><td>Card Type</td><td>Last 4</td></tr>
	<?php 

		foreach ($transactions as $id => $transaction)
		{
			echo '<tr><td><a href="index.php?transaction='.$transaction->id.'">'.$transaction->id.'</a></td><td>'.$transaction->amount.'</td><td>'.$transaction->cardType.'</td><td>'.$transaction->last4.'</td></tr>';
		}

	?>
</table>

</body>
</html>

And the next file show a single transaction by using its Id:

<html>
<head></head>
<body>
<?php 
	echo 'Id:        ' . $transaction->id. '<br/>';
	echo 'Amount:    ' . $transaction->amount. '<br/>';
	echo 'Card Type: ' . $transaction->cardType. '<br/>';
	echo 'Last 4:    ' . $transaction->last4. '<br/>';
?>
</body>
</html>

Controller

The Controller receives the request, parses it, and then it initializes and invokes the Model. The Controller, then, takes the model response and sends it to the View layer. It’s practically the bridge between the Model and the View. The application entry point is index.php. The index.php file delegates all the requests to the Controller.

<?php
include_once("model/Model.php");
class Controller {
	public $model;
	
	public function __construct()  
    {  
        $this->model = new Model();

    } 
public function invoke()
	{
		if (!isset($_GET['transaction']) || empty($_GET['transaction']))
		{
			//list of all available transactions

			$transactions = $this->model->getTransactionList();
			include 'view/transactionlist.php';
		}
		else
		{
			// only the requested transaction			
			$transaction = $this->model->getTransaction($_GET['transaction']);
			include 'view/viewtransaction.php';
		}
	}
}
?>

Our Controller class has just one function and its constructor. The constructor instantiates a model class, and for each request, the Controller decides about the required data from the Model. The Controller calls the Model class to retrieve the data.
The Controller does not know anything about the database or about how the results page created or works.

MVC model has at least the following advantages:

  • The Model and View can be changed separately or replaced. The independence of the components allows us to upgrade or update applications with ease.
  • Separation of The Model and View makes the application more flexible.
  • Database and data management securely tucked away. You can even switch your database server without making any changes to your application UI (the View) or the Model.
  • Each component and its code can be tested and debugged separately.

Kourosh

Your Header Sidebar area is currently empty. Hurry up and add some widgets.