Fork me on GitHub

Controllers

Prerequisite

Prerequisite for this section that were previously discussed in routing & pretty URLs section:

Basics

Controller is a PHP class located in controller folder of an application and is suffixed with "Controller" e.g. blogController.

A controller takes a request, does something on it and returns a response object hathoora/http/response

Sample controller code is shown below.

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

            namespace appNAME\controller;
            use hathoora\controller\controller;

            /**
             * Default controller
             */
            class defaultController extends controller
            {
                /**
                 * Homepage action
                 */
                public function index()
                {
                    // assign variables to template
                    $arrTplVars = array(
                        'time' => time()
                    );

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

                    return $response;
                }
            }
        
    

In this example we are extending hathoora\controller\controller and by doing so our controller gets access to container.

Barebone Controller

Above example can also be coded as following without extending hathoora\controller\controller.

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

            namespace appNAME\controller;

            /**
             * Default controller
             */
            class defaultController extends controller
            {
                /**
                 * Homepage action
                 */
                public function index()
                {
                    // assign variables to template
                    $arrTplVars = array(
                        'time' => time()
                    );

                    $template = new \hathoora\template\template('index.tpl.php', $arrTplVars);
                    $response = new \hathoora\http\response($template);

                    return $response;
                }
            }
        
    

Global Template Variables

Often time variable needs to be assigned globally throughout included templates. This is achieved by using setTplVarsByRef and setTplVars as shown below.

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

            namespace appNAME\controller;
            use hathoora\controller\controller;

            /**
             * Blog controller
             */
            class blogController extends controller
            {
                public function index()
                {
                    // assigning global template variables
                    $this->setTplVarsByRef('user', $this->user);
                    $this->setTplVars('userFlag', 1);

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

                    /**
                     * index.tpl would would have following three variables available in this example
                     *  - user
                     *  - userFlag
                     *  - time
                     */
                    $template = $this->template('index.tpl.php', $arrTplVars);

                    $response = $this->response($template);

                    return $response;
                }
            }
        
    

Base Controllers

The above example of defining global template variables can also be achived by using a base controller, where the name 'base' can by anything.

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

            namespace appNAME\controller;
            use hathoora\controller\controller;

            /**
             * base controller
             */
            class baseController extends controller
            {
                public function __construct()
                {
                    $this->user = $this->getUser();

                    // assigning global template variables
                    $this->setTplVarsByRef('user', $this->user);
                    $this->setTplVars('userFlag', 1);
                }
            }



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

            namespace appNAME\controller;

            /**
             * Blog controller
             */
            class blogController extends baseController
            {
                public function __construct()
                {
                    parent::__construct();
                }

                public function index()
                {
                    $arrTplVars = array(
                        'time' => time()
                    );

                    /**
                     * index.tpl would would still have following three variables available in this example
                     *  - user
                     *  - userFlag
                     *  - time
                     */
                    $template = $this->template('index.tpl.php', $arrTplVars);

                    $response = $this->response($template);

                    return $response;
                }
            }
        
    

Accessing Globals (GET, POST, SERVER, SESSION, COOKIE etc.)

These can be obtained from hathoora/http/request::make() object. If your controller is extending hathoora\controller\controller then you can also use the following built-in functionality.

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

            namespace appNAME\controller;
            use hathoora\controller\controller;

            /**
             * blog controller
             */
            class blogController extends controller
            {
                public function list()
                {
                    $request = $this->getRequest();

                    // equvilant to $_GET['q'] with ability to default to a value
                    $q = $request->getParam('q', 'default value');

                    // equvilant to $_POST['q'] with ability to default to a value
                    $q = $request->postParam('q', 'default value');

                    // equvilant to $_SERVER['HTTP_HOST']
                    $x = $request->serverParam('http_host');

                    // equvilant to returning the value of $_SESSION['param']
                    $v = $request->sessionParam('param');

                    // equvilant to $_SESSION['param'] = 'value'
                    $request->sessionParam('param', 'value');

                    // get cookie value
                    $cookie = $request->cookieParam('param');

                    // store cookie
                    $request->cookieParam('param', 'value', 300, $path = '/', $domain = null);

                    ...
                }
            }
        
    

Click here to view complete list of functions avaialble in request object.

Accessing Container

If your contoller is extending hathoora/container/* then you have access to container within the scope of controller.

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

            namespace appNAME\controller;
            use hathoora\controller\controller;

            /**
             * blog controller
             */
            class blogController extends controller
            {
                public function list()
                {
                    // 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();

                    ...
                }
            }
        
    

If you are using barebone controller, the you can access container by doing something like the following:

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

            namespace appNAME\controller;
            use hathoora\container;

            /**
             * blog controller
             */
            class blogController
            {
                public function list()
                {
                    // check for GET param
                    $q = container::getRequest()->getParam('q');

                    // get current application path
                    container::getRouteRequest()->getAppDirectory();

                    // check for configuration
                    container::getConfig('myconfigName');

                    // setting a config
                    container::setConfig('myconfigName', 'value1');

                    // Hathoora PHP Framework version
                    container::getKernel()->getKernel();

                    ...
                }
            }
        
    

Sending Custom Headers In Response

Following example demonstrates sending custom headers in response.

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

            namespace appNAME\controller;
            use hathoora\controller\controller;

            /**
             * blog controller
             */
            class blogController extends controller
            {
                public function list()
                {
                    $request = $this->getRequest();

                    // get HTML from a template
                    $html = $this->template('index.tpl.php');
                    // or it can be as simple as the following
                    $html = 'Hello World';

                    // send following headers back to the client
                    $arrHeaders = array(
                        'Access-Control-Allow-Method' => 'GET, POST',
                        'Header1' => 'Value1'
                    );

                    // send HTTP status code, the default is 200
                    $httpStatusCode = 200;
                    $response = $this->response($html, $arrHeaders, $httpStatusCode);

                    return $response;
                }
            }
        
    

Redirects and Flash Messages

A flash message is used in order to keep a message in session through one or several requests of the same user. By default, it is removed from session after it has been displayed to the user. Flash messages are usually used in combination with HTTP redirections, because in this case there is no view, so messages can only be displayed in the request that follows redirection.

Following example demonstrates setting flash message and redirects.

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

            namespace appNAME\controller;
            use hathoora\controller\controller;

            /**
             * blog controller
             */
            class blogController extends controller
            {
                public function list()
                {
                    ...

                    $response = $this->response();

                    if (!$user)
                    {
                        // other types can be error, warning, anything..
                        $response->setFlash('Please Login to continue.', 'info');

                        $url = '/';
                        $response->redirect($url, 301);
                    }
                    else
                    {
                        $template = $this->template('index.tpl.php');
                        $response->setContent($template);
                    }

                    return $response;
                }
            }
        
    

Flash messages are stored in session under the name httpFlash. They can then be rendered inside template by doing something like the following

        
            # File - Stuob template

            $arrMessages = $this->getFlashMessage();
            $arrCheckThese = array(
                'info', 'error', 'warning', 'success'
            );
            foreach ($arrCheckThese as $type)
            {
                if (isset($$type))
                    $arrMessages[$type] = $$type;
            }

            if (is_array($arrMessages))
            {
                foreach ($arrMessages as $type => $arrMessage)
                {
                    echo '
                    <div class="flash '. $type .'">';

                        if (is_array($arrMessage) || is_object($arrMessage))
                        {
                            echo '<p>Sorry an error occured while trying to process your request.</p>';
                            echo '<ul>';
                            foreach ($arrMessage as $k => $v)
                            {
                                echo '<li class="'. $k .'">' . $v . '</li>';
                            }
                            echo '</ul>';
                        }
                        else
                            echo '<p>'. $arrMessage .'</p>';

                    echo '
                    </div>';
                }
            }
        
    

RESTful Controller

RESTful controllers are achieved by extending hathoora\controller\CRUD and using the following convention (for a chat room endpoint).

  • Getting list of records -> GET /room -> collection()
  • Getting record info -> GET /room/12 -> read($id)
  • Creating new record -> POST /room -> create()
  • Updating existing record -> UPDATE /room/12 -> update($id)

Consider a sample class which demonstrate this.

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

            namespace appNAME\controller;
            use hathoora\controller\CRUD;

            /**
             * room api controller
             */
            class roomController extends CRUD
            {
                /**
                 * URL: GET /room to return list of all rooms
                 */
                public function collection()
                {
                    //
                }

                /**
                 * GET /room/12 - Retrieves a specific room
                 */
                public function read($id = null)
                {
                    //
                }

                /**
                 * POST /room - Creates a new room
                 */
                public function create()
                {
                    //
                }

                /**
                 * PUT /room/12 - Updates room #12
                 */
                public function update($id)
                {
                    //
                }

                /**
                 * DELETE /room/12 - Deletes ticket #12
                 */
                public function delete($id)
                {
                    //
                }
            }
        
    

hathoora\controller\CRUD doesn't have any implementation for authentication or sending appropriates headers, you would have to create one that meet your needs.

Page Took:         3.66 msec
Page Memory:   563.08k
docs / viewController / view (200)
Request UUID: 594f776070fbf9.52939874
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
hathoora.org
HTTP_X_FORWARDED_FOR
54.81.154.223
HTTP_X_REAL_IP
54.81.154.223
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 hathoora.org Port 80
SERVER_SOFTWARE
Apache/2.2.15 (CentOS)
SERVER_NAME
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
32926
REDIRECT_URL
/docs/v1/controller
GATEWAY_INTERFACE
CGI/1.1
SERVER_PROTOCOL
HTTP/1.0
REQUEST_METHOD
GET
QUERY_STRING
REQUEST_URI
/docs/v1/controller
SCRIPT_NAME
/index.php
PHP_SELF
/index.php
REQUEST_TIME_FLOAT
1498380128.462
REQUEST_TIME
1498380128
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 1.870 DEBUG 309.31 Configuration loaded:
Array
(
    [0] => app_prod.yml
    [1] => config_prod.yml
)
2 1.987 DEBUG 322.92 Listener "kernel.terminate[webprofiler]" has been added because of hathoora.logger.webprofiler.enabled
3 2.062 DEBUG 326.31 Event kernel.ready has been registered.
4 2.148 DEBUG 334.68 Calling App dispatcher (Array ( [class] => customDispatcher [method] => dispatch ) )...
5 2.218 DEBUG 348.99 Event kernel.route has been registered.
6 2.326 DEBUG 378.34 Event kernel.controller has been registered.
7 2.348 DEBUG 379.28 Calling controller (\docs\controller\viewController::view) with following params
Array
(
    [0] => v1
    [1] => controller
)
8 2.611 INFO 466.64 Template (docs/v1/controller.tpl.php) loaded
9 2.710 INFO 516.16 Template (/var/websites/hathoora.org/app/hathoora/docs//resources/templates/components/htmlMeta.tpl.php) loaded
10 2.762 INFO 517.41 Template (/var/websites/hathoora.org/app/hathoora/docs//resources/templates/components/flashMessages.tpl.php) loaded
11 3.487 INFO 451.35 Template (docs.tpl.php) fetched.
12 3.514 DEBUG 450.95 Event kernel.response has been registered.
13 3.531 DEBUG 452.13 Event kernel.terminate has been registered.
14 3.578 DEBUG 455.35 Event kernel.terminate->webprofiler has been notified.
Profiling
template
# Time (msec) Name Cached Took (msec)
1 2.393 docs.tpl.php 0 1.037