PHP Views

Views are files that create the HTML to be sent to the browser. They are composed of HTML, JavaScript, CSS and PHP variables passed in from the controller.

PHP within views performs minimalistic logic, only using if statements, loops, utility functions, and echoing out variables.

Types of Views


MogulMVC has two main types of views, views and templates.

Views are full pages, minus the head, header, footer, foot, which closes the head. They are essentially just the content of the page.

Templates are reusable UI elements. For example, each section element within this document is a template file. It can be reused as many times as needed and minimize the amount of code that needs to be written.

Create a View


To create a view first start by creating HTML.

<div>
	<p>Welcome Back User Name</p>
</div>

Once happy with the view replace all sections needing dynamic data with a PHP echo statement.

<div>
	<p>Welcome Back <?php echo $user_name; ?></p>
</div>

In this example $user_name would be a variable passed in from the controller. In reality views contain far more HTML than the example above.

Templates are created the same way as views. However as templates are only sections of a page they are more minimalistic.

Load a View


Loading views happens in the controller using the MLoad class. Within the MLoad class there are four functions created to load different types of views. These are view, page, template_application, and template_framework.

The view function loads a view from the view directory. It will include the head, header, footer, and foot template files you configured within your config.php file within the config directory.

The page function will do nearly the same thing as the view function. However, only the head and foot will be loaded for a page.

The template_application and template_framework do the same thing but load from different locations. The template_application function loads a view from the backend/view directory. The template_framework function loads a view from the backend/framework/view directory.

MogulMVC has some built in templates which it uses when loading in CSS JavaScript.

All the view loading functions accept two parameters, the second being optional.

The first parameter is the file to load, starting from the view directory in all but the template_framework's case. The second parameter is an associative array, containing all variables you wish to use within the view.

Assume we have a associative array declared within the controller which has several indexes. That associative array would be passed a view as follows.

$data["user_id"] = 10;
$data["user_name"] = "John Smith";

MLoad::view("my_view", $data);

Each index within that associative array would become a declared variable within the view.

$data["user_id"] becomes $user_id and $data["user_name"] becomes $user_name.