Fork me on GitHub

View & Templates

Prerequisite

Prerequisite for this section that were previously demonstrated in controller section:

Basics

In Hathoora PHP Framework there is no technical difference between a view and template. View is usually a collection of templates. Template is where you would render HTML and this HTML is then injected into response object.

Templates are located in HATHOORA_ROOTPATH/app/appNAME/resources/templates folder.

An example of how a template is used from controller is shown below.

        
            # File HATHOORA_ROOTPATH/app/appNAME/controller/defaultController.php

            namespace site\controller;
            use hathoora\controller\controller;

            /**
             * Default controller
             */
            class defaultController extends controller
            {
                /**
                 * Homepage action
                 */
                public function index()
                {
                    // assign variables to template
                    $arrTplVars = array(
                        'title' => 'My Website',
                        'date' => date('m/d/y')
                    );

                    $template = $this->template('index.tpl.php', $arrTplVars);
                    $response = $this->response($template);

                    return $response;
                }
            }
        
    

In this example HATHOORA_ROOTPATH/app/appNAME/resources/templates/index.tpl.php will be used which may look like the following.

        
            # File HATHOORA_ROOTPATH/app/appNAME/resources/templates/index.tpl.php
            # This template is using Stuob template which is plain ole' PHP

            <html>
                <title><?php echo $title ;?></title>
            </html>
            <body>
                <!-- and using PHP's shorthand notation, inestead of echo, you can use <?= $var; ?> -->
                Today's date: <?= $date; ?>
            </body>
            </html>
        
    

In above example $title and $date were dynamic variables assigned via controller.

Templatize From Anywhere

Templates can be used from anywhere and are not restricted to controller. Suppose if a HTML table needs to be rendered by a logical function, then you can do something like the following:

        
            # File HATHOORA_ROOTPATH/app/appNAME/logic/myLogic.php
            namespace appNAME\logic;
            use hathoora\model\model;

            class myLogic extends model
            {
                /**
                 * This function returns
                 */
                public static function getTableHTML()
                {
                    ...

                    // full path of current app (which is appNAME)
                    $route = $this->getRouteRequest();
                    $appPath = $route->getAppDirectory() . '/resources/templates/';
                    $templatePath = $appPath . 'components/table.tpl.php';

                    $db = $this->getDBConnection();
                    $arrData = $db->fetchArrayAll('....')

                    $arrTplVars = array(
                        'arrData' => $arrData
                    );

                    $template = new \hathoora\template\template($templatePath, $arrTplVars);

                    return $template->fetch();
                }
            }


            # File HATHOORA_ROOTPATH/app/appNAME/resources/templates/components/table.tpl.php
            <table>
                <tr>
                    <th>Date</th>
                    <th>Message</th>
                </tr>
                <?php
                    foreach ($arrData as $_arr)
                    {
                        echo '
                            <tr>
                                <td>'. $_arr['date'] .'</td>
                                <td>'. $_arr['message'] .'</td>
                            </tr>';
                    }
                ?>
            </table>
        
    

Using Templates From Other Apps

If you have multiple applications then you can use templates from one application into another. Consider the following example:

        
            # File HATHOORA_ROOTPATH/app/appNAME/controller/defaultController.php

            namespace site\controller;
            use hathoora\controller\controller;

            /**
             * Default controller
             */
            class defaultController extends controller
            {
                /**
                 * Homepage action
                 */
                public function index()
                {
                    // assign variables to template
                    $arrTplVars = array(
                        'title' => 'My Website',
                        'date' => date('m/d/y')
                    );

                    // full path of other app
                    $route = $this->getRouteRequest();
                    $appPath = $route->getAppDirectory('otherAPPName') . '/resources/templates/';
                    $templatePath = $appPath . 'layout.tpl.php';

                    $template = $this->template($templatePath, $arrTplVars);
                    $response = $this->response($template);

                    return $response;
                }
            }
        
    

In this example we are using container's $this->getRouteRequest()->getAppDirectory() method to get absoulte path of other app. But you can also hard code path (if needed).

Template Engines

You have the ability to choose which template engine to use. The default enging is Stuob. Template engine is defined like so.

        
            # File HATHOORA_ROOTPATH/app/appNAME/config/config_HATHOORA_ENV.yml

            # framework configurations..
            hathoora:
                ...
                template:
                    engine:
                        name: Stuob
                ...
        
    

Stuob (Default template engine)

Stuob is the default template engine which is plain PHP inside templates.


Configuration
Following demonstrate how to configure Stuob per application.

        
            # File HATHOORA_ROOTPATH/app/appNAME/config/config_HATHOORA_ENV.yml

            # framework configurations..
            hathoora:
                ...
                template:
                    engine:
                        name: Stuob
                    Stuob:
                        caching: 0|1
                        cache_dir:  writeable absoulte path to where cache content is stored
                        cache_lifetime: INT in seconds, how long to cache for
                ...
        
    

Caching
In addition to above configurations, you can also define Stuob caching parameters as shown below in this cache example.

        
            $arrTplVars = array(
                'name' => 'Hathoora'
            );
            $template = \hathoora\template\template('cacheTemplate.tpl.php', $arrTplVars);
            $template->setCacheDir('/tmp/cache');
            $template->setCacheId(8171);
            $template->setCacheTime(60);
            $template->setCaching(true);

            if ($template->isCached())
            {
                //echo "File is cached ";
            }
            else
            {
                // do heavy duty stuff
                $data = ...

                $template->assign('moreVars', $data);
            }

            $html = $template->fetch();
        
    

Extending Templates
Templates can be extended using block(), start(), end() and extend() functions as demonstrated in the following example.

        
            # File layout.tpl.php

            <!doctype html>
            <html>
            <head>
                <meta charset="utf-8">
                <title>
                    <?php
                        $this->block('metaTitle');
                    ?>
                </title>
            </head>
            <body class=" ">
                <div id="container">
                    <div id="body">
                        <?php
                            $this->block('body');
                        ?>
                    </div>
                    <div id="footer"> </div>
                 </div>
            </body>
            </html>


            # File children.tpl.php

            <?php
            $this->start('metaTitle');
                echo 'Website Title';
            $this->end('body');

            $this->start('body');
                echo '<div>Body</div>';
            $this->end('body');

            $this->extend('layout.tpl.php');
        
    

Above would produce the following:

        
            <!doctype html>
            <html>
            <head>
                <meta charset="utf-8">
                <title>
                    Website Title
                </title>
            </head>
            <body class=" ">
                <div id="container">
                    <div id="body">
                        <div>Body</div>
                    </div>
                    <div id="footer"> </div>
                 </div>
            </body>
            </html>
        
    

Including Templates
Use load($file, $tplVars) to include a template into another.


Rendering A Controller
To render a controller from template using render($arrController, $args) as demonstrated in the following example.

        
            # File layout.tpl.php

            <!doctype html>
            <html>
            <head>
                <meta charset="utf-8">
                <title>
                    <?php
                        $this->block('metaTitle');
                    ?>
                </title>
            </head>
            <body class=" ">
                <div id="userBar">
                    <?php $this->render(array(
                                                    '\myNameSpace\controller\structureController', // class name
                                                    'topBar'    // action (method) name
                                                ),
                                                array('param2', 'param2') // arguments to pass to method
                                            );
                    ?>
                </div>
                <div id="container">
                    <div id="body">
                        <?php
                            $this->block('body');
                        ?>
                    </div>
                    <div id="footer"> </div>
                 </div>
            </body>
            </html>
        
    

Accessing Container
By default you have access to container within the scope of template. Consider the following demonstration.

        
            # File layout.tpl.php

            ...

            // check for GET param
            $q = $this->getRequest()->getParam('q');

            // get current application path
            $this->getRouteRequest()->getAppDirectory();

            // check for configuration
            $this->getConfig('myconfigName');

            // setting a config
            $this->setConfig('myconfigName', 'value1');

            // Hathoora PHP Framework version
            $this->getKernel()->getKernel();

            ...
        
    

Smarty

To be documented...

Page Took:         6.41 msec
Page Memory:   548.1k
docs / viewController / view (200)
Request UUID: 599cce5482d5f4.36519862
Get
Post
Cookies
Files
Session
Server
Response
No data.
No data.
No data.
No data.
No data.
REDIRECT_HATHOORA_ENV
prod
REDIRECT_STATUS
200
HATHOORA_ENV
prod
HTTP_HOST
www.hathoora.org
HTTP_X_FORWARDED_FOR
54.166.205.242
HTTP_X_REAL_IP
54.166.205.242
HTTP_CONNECTION
close
HTTP_ACCEPT_ENCODING
x-gzip, gzip, deflate
HTTP_USER_AGENT
CCBot/2.0 (http://commoncrawl.org/faq/)
HTTP_ACCEPT
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
PATH
/sbin:/usr/sbin:/bin:/usr/bin
SERVER_SIGNATURE
Apache/2.2.15 (CentOS) Server at www.hathoora.org Port 80
SERVER_SOFTWARE
Apache/2.2.15 (CentOS)
SERVER_NAME
www.hathoora.org
SERVER_ADDR
192.168.1.11
SERVER_PORT
80
REMOTE_ADDR
207.126.164.119
DOCUMENT_ROOT
/var/websites/hathoora.org/docroot
SERVER_ADMIN
webmaster@hathoora.org
SCRIPT_FILENAME
/var/websites/hathoora.org/docroot/index.php
REMOTE_PORT
37848
REDIRECT_URL
/docs/v1/view
GATEWAY_INTERFACE
CGI/1.1
SERVER_PROTOCOL
HTTP/1.0
REQUEST_METHOD
GET
QUERY_STRING
REQUEST_URI
/docs/v1/view
SCRIPT_NAME
/index.php
PHP_SELF
/index.php
REQUEST_TIME_FLOAT
1503448660.535
REQUEST_TIME
1503448660
Status: 200
Headers:
Content-Type
text/html; charset=UTF-8
Configutation
Key Value
app.admin
Array
(
    [pattern] => /admin(|/)
    [directory] => hathoora
    [namespace] => hathoora\admin
)
app.docs
Array
(
    [pattern] => /docs(|/)
    [directory] => hathoora
    [dispatcher] => Array
        (
            [class] => customDispatcher
            [method] => dispatch
        )

)
app.site
Array
(
    [default] => 1
)
hathoora.logger
Array
(
    [profiling] => Array
        (
            [enabled] => 1
        )

    [logging] => Array
        (
            [enabled] => 1
            [level] => DEBUG
        )

    [webprofiler] => Array
        (
            [enabled] => 1
            [system] => 
            [show_redirects] => 
        )

)
hathoora.template
Array
(
    [engine] => Array
        (
            [name] => Stuob
        )

)
hathoora.database
Array
(
    [default] => mysql://dbuser:dbpassword@dbhost:3306/dbname
)
services.container
Array
(
    [class] => \hathoora\container
    [method] => getContainer
)
Logging (14)
hathoora.logger.logging.enabled: 1
# Time (msec) Level Memory (KB) Message
1 2.328 DEBUG 309.28 Configuration loaded:
Array
(
    [0] => app_prod.yml
    [1] => config_prod.yml
)
2 2.613 DEBUG 322.89 Listener "kernel.terminate[webprofiler]" has been added because of hathoora.logger.webprofiler.enabled
3 2.769 DEBUG 326.28 Event kernel.ready has been registered.
4 2.973 DEBUG 334.65 Calling App dispatcher (Array ( [class] => customDispatcher [method] => dispatch ) )...
5 3.129 DEBUG 348.96 Event kernel.route has been registered.
6 3.380 DEBUG 378.30 Event kernel.controller has been registered.
7 3.443 DEBUG 379.25 Calling controller (\docs\controller\viewController::view) with following params
Array
(
    [0] => v1
    [1] => view
)
8 4.032 INFO 466.59 Template (docs/v1/view.tpl.php) loaded
9 4.255 INFO 505.31 Template (/var/websites/hathoora.org/app/hathoora/docs//resources/templates/components/htmlMeta.tpl.php) loaded
10 4.388 INFO 506.56 Template (/var/websites/hathoora.org/app/hathoora/docs//resources/templates/components/flashMessages.tpl.php) loaded
11 6.008 INFO 447.70 Template (docs.tpl.php) fetched.
12 6.069 DEBUG 447.30 Event kernel.response has been registered.
13 6.110 DEBUG 448.48 Event kernel.terminate has been registered.
14 6.221 DEBUG 451.70 Event kernel.terminate->webprofiler has been notified.
Profiling
template
# Time (msec) Name Cached Took (msec)
1 3.546 docs.tpl.php 0 2.340