Categories
MVC PHP

An Introduction to Views

MVC application output is defined in views. Four our PHP MVC application, these views are defined as .php files which mainly contain HTML/CSS/JavaScript code and some PHP to output model elements as required.

It is important to note here that the output formats depend on the application we are trying to build. For example, some applications, APIs, will output JSON data only and leave it up to a separate front-end to render the UI.

Going back to our example, let’s take a look at a simple view, itemList.php, stored in the /app/views/home/ folder:

<html>
<head><title>Item List</title></head>
<body>
<h1>List of items</h1>
<ul>
<?php
  foreach($data['items'] as $item){
    echo "<li>$item->name</li>";
  }
?>
</ul>
</body>
</html>

Much of the above view is directly output HTML code. However, the code between <?php ... ?> generates one <li>...</li> element per item in the $data[‘items’] collection passed to the view by the controller. The foreach loop is one of the most often used repetition instructions in PHP Views. For more information on all that can be done to produce correct output, refer to Hello PHP! and PHP: Getting Acquainted.

The main concern addressed by the Views is to format the data output as per the requirements for the application. This formatting is not a concern that the Model or Controller classes share. Concerns are task categories that should be handled by different classes when the separation of concerns is done correctly.

Tying this to the previous examples

Consider the following controller calling the above-defined view in its index method:

class HomeController extends Controller{
public function index(){
$items = $this->model('item')->get();
$this->view('home/itemList',['items'=>$items])
}
}

The above gets data from the storage and access interface through the call to $this->model('item')->get(). We assume item elements contain a name attribute. Then, this data is passed to the view on the following line. Notice how the view name is the folder and file name (less the .php) from the /app/views/ folder.

In the next post, we will look at building a model base class and model item class to match our example.

By Michel

My name is Michel Paquette. I currently teach my students how to create data-driven Web applications at Vanier College, in Montreal.

My GitHub page contains a few examples of Web applications. Also consult my YouTube channels: @CSTutoringDotCa and @MichelPaquette.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.