Application Views
Application Views
Views in Hazaar MVC are the presentation layer of your application. They are responsible for generating the output that is sent to the user. This is typically HTML, but it can be any format such as XML, JSON, or text.
How it works
The view system is managed by the Hazaar\Controller\Action controller. When an action method is executed, it can load a view and pass data to it. The view is then rendered and sent as the response.
The Action controller has a public property $view which is an instance of Hazaar\Controller\Action\ViewRenderer. This renderer handles the loading, data management, and rendering of the actual view files.
The View Renderer
The ViewRenderer provides several methods to interact with views from your controller:
view(string $view, array $data = []): Loads a view file and optionally sets data.layout(string $view): Sets a layout view (see below).__set(string $key, mixed $value): Sets data available to the view.__get(string $key): Retrieves data or view helpers.
Loading a View
To load a view from your controller, call the view() method:
public function index()
{
$this->view('index');
}This will look for a view file named index (e.g., index.tpl or index.phtml) in the application/views directory.
Passing Data to Views
You can pass data to views in two ways:
As a parameter to
view():$this->view('index', ['message' => 'Hello World!']);Using the set() method on
$this->view:$this->view->set('message', 'Hello World!'); $this->view('index');
Both methods result in the variable $message being available in your template.
Template Engines
Hazaar supports widely used template engines and allows you to mix and match them.
- Smarty: A robust template engine separating business logic from presentation. Uses
.tplfiles. - PHTML: Standard PHP files used as templates. Uses
.phtmlfiles.
The framework automatically detects the engine based on the file extension. You can use a Smarty layout with a PHTML view, or vice versa; the framework handles the interoperability seamlessy.
Layouts
Layouts are special views that wrap your main view content, useful for defining a common structure (header, footer, navigation).
Configuration
You can define a default layout in your application configuration (e.g., app/configs/app.php):
'action' => [
'layout' => 'application.tpl'
]This tells the controller to automatically wrap all views in the application.tpl layout.
Changing Layouts
You can change the layout for a specific action dynamically:
public function login()
{
$this->layout('login'); // Uses login.tpl or login.phtml
$this->view('login');
}Or disable it entirely for that request:
$this->view->setNoLayout();