Crater PHP Framework

fast, lightweight and modular

Views

Views are the visual side of the framework, they are the html output of the pages. All views are located in the views folder. The actual views can be located directly inside the views folder or in a sub folder, this helps with organising your views.

Views are called from controllers once called they act as included files outputting anything inside of them. They have access to any data passed to them from a data array or with object setter.

render() is the primary method of View Class.

Using a view from a controller

public function indexAction()
{
    $viewVariables = array(
        'title' => 'Hello Crater',
        'message' => 'How are you?',
        'options' => array(
            'good',
            'pretty good',
            'bad',
            'very bad'
        )
    );

    $this->view->another_variable = 'This is another variable.';

    return $this->view->render('hello/index', $viewVariables);
}

So, in index action, you already have the View object. All you have to do is to set variables and specify the name of view file

As you can see, you have two ways to set the variables. With an array or with object setter.

At line 10, you rend view from: App/Views/hello/index.phtml

Note: All view files and template file, should have .phtml extension.

Views are normal php files they can contain php and html, as such any php logic can be used inside a view though its recommended to use only simple logic inside a view anything more complex is better suited inside a controller.

For the above data we have the following content:

<div>
    <h1><?php echo $this->title?></h1>
    <h2><?php echo $this->message?></h2>
    <ul>
        <?php foreach ($this->options as $option):?>
            <li><?php echo $option?></li>
        <?php endforeach?>
    </ul>
</div>

Add headers

If you want to send a raw HTTP header, you can use addHeader() or addHeaders() methods.

$this->view->addHeader('Content-Type: application/pdf')

or

$headers = array(
    'Cache-Control: no-cache, must-revalidate',
    'Expires: Sat, 26 Jul 1997 05:00:00 GMT'
);

$this->view->addHeaders($headers);

JSON Response

If you want to have a JSON Response on an action, you can use jsonResponse() method.

$data = array(
    "content" => array(
        "first_var" => "foo",
        "second_var" => "bar"
    ),
    "success" => true
);

return $this->view->jsonResponse($data);