Fork me on GitHub

Listeners

Basics

To understand listeners, lets go through basic terminology:

  • Event: is an action.
  • Subject: the object responsible for event.
  • Listener: is a php class whose method would react to subject when an event occurs.

Listeners are handled by hathoora\observer class.

Registering A Listener

To understand listeners, lets go through basic terminology:

You can define listeners in configuations like so:

        
            # File config.yml

            listeners:
                note.save:
                    updateCache:
                        class: \namespace\cacheClass
                        method: functionToCache

                    logIt:
                        class: \namespace\logClass
                        method: functionToLog
        
    

In this example when we added two listeners for an event called note.save:

  • updateCache: is a listener which is an instance of \namespace\cacheClass and whose method functionToCache will be called.
  • logIt: is a listener which is an instance of \namespace\logClass and whose method functionToLog will be called.
:

Runtime (Un)Register

In addition to registering listeners in configuration, you can also register them during run time. So to add above listeners in runtime you can use addListener like so:

        
            $observer = \hathoora\container::getObserver();

            $observer->addListener('note.save', 'updateCache',
                                    array(
                                        'class' => '\namespace\cacheClass',
                                        'method' => 'functionToCache'));

            $observer->addListener('note.save', 'logIt',
                                    array(
                                        'class' => '\namespace\logClass',
                                        'method' => 'functionToLog'));
        
    

In order to remove a listener runtime, you can use the removeListener method.

        
            $observer = \hathoora\container::getObserver();

            $observer->removeListener('note.save', 'updateCache');
            $observer->removeListener('note.save', 'logIt');
        
    

Registering An Event

Continue above example, to register an event for listeners to act on, you can do something like this:

        
            $subject = new \Note();

            $observer = \hathoora\container::getObserver();
            $observer->addEvent('eventName', $subject);
        
    

In this example we registered an event called eventName and we are passing $subject to our listeners (via referrence).

Listener In Action

Following shows sample code for what listeners would look like for above configuration:

        
            # File \namespace\cacheClass
            class cacheClass
            {
                public function functionToCache(\Note &$note)
                {
                    // cache it

                    // modify subject
                    $note->cached = true;
                }
            }


            # File \namespace\logClass
            class logClass
            {
                public function functionToLog(\Note &$note)
                {
                    // log it

                    var_dump($note->cached); // is bool true
                }
            }
        
    

In this example the subject \Note $note is passed to listener method's via referrences.

Kernel Events

Hathoora PHP Framework has built-in events that are fired through the life cycle of request. It gives you the flexibility to hook on to these events to change the behaviour.

  • kernel.ready: this event is fired when Hathoora PHP Framework has bootstrapped the application and loaded configurations and about to dispatch request. Use cases of this event could be:
    • Start a custom session
    • Throttling logic
    • Check of high level application access (based on session/ip/etc)

  • kernel.route: this event is fired when router has been figured out and we know which controller to route request to. Use cases of this event could be:
    • To say redirect user to a recaptcha page.
    • Redirect unregistered user's to a signup controller.
    • Use for displaying landing pages.
    In most cases you would need to overwrite $kernel->routeDispatcher for this event.
  • kernel.controller: when controller's action is executable and is about to be executed. Use cases of this event could be the same as kernel.route with addition to:
    • Do logic basic on controller name.
    • Do controller/action access logic for a DB driven permission system.
    In most cases you would need to overwrite $kernel->controller = new controller($kernel->routeDispatcher) for this event.
  • kernel.route_unreachable: when controller's action is not executable (possible 404). Use cases of this event could be:
    • Show pretty 404 pages.
    In this event you can either overwrite $kernel->controller = new controller($kernel->routeDispatcher) or simple have your listener return a \hathoora\http\response object.
  • kernel.response: when we have a response object from controller's action. Use cases of this event could be:
    • Trim whitespaced from response.
    • Pass headers back in response.
    In most cases you would need to overwrite/modify $kernel->response for this event.
  • kernel.terminate: event is fired when request has reached its end. Use cases of this event could be:
    • Profilling your application.

For all above kernel events, the subject passed to listeners is container.

Page Took:         6.33 msec
Page Memory:   526.21k
docs / viewController / view (200)
Request UUID: 599cce628ea2b8.58146788
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
38068
REDIRECT_URL
/docs/v1/listeners
GATEWAY_INTERFACE
CGI/1.1
SERVER_PROTOCOL
HTTP/1.0
REQUEST_METHOD
GET
QUERY_STRING
REQUEST_URI
/docs/v1/listeners
SCRIPT_NAME
/index.php
PHP_SELF
/index.php
REQUEST_TIME_FLOAT
1503448674.583
REQUEST_TIME
1503448674
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.312 DEBUG 309.34 Configuration loaded:
Array
(
    [0] => app_prod.yml
    [1] => config_prod.yml
)
2 2.588 DEBUG 322.95 Listener "kernel.terminate[webprofiler]" has been added because of hathoora.logger.webprofiler.enabled
3 2.756 DEBUG 326.34 Event kernel.ready has been registered.
4 2.957 DEBUG 334.71 Calling App dispatcher (Array ( [class] => customDispatcher [method] => dispatch ) )...
5 3.116 DEBUG 349.02 Event kernel.route has been registered.
6 3.387 DEBUG 378.37 Event kernel.controller has been registered.
7 3.437 DEBUG 379.31 Calling controller (\docs\controller\viewController::view) with following params
Array
(
    [0] => v1
    [1] => listeners
)
8 4.036 INFO 466.66 Template (docs/v1/listeners.tpl.php) loaded
9 4.326 INFO 487.24 Template (/var/websites/hathoora.org/app/hathoora/docs//resources/templates/components/htmlMeta.tpl.php) loaded
10 4.499 INFO 488.49 Template (/var/websites/hathoora.org/app/hathoora/docs//resources/templates/components/flashMessages.tpl.php) loaded
11 5.911 INFO 441.73 Template (docs.tpl.php) fetched.
12 5.974 DEBUG 441.32 Event kernel.response has been registered.
13 6.016 DEBUG 442.51 Event kernel.terminate has been registered.
14 6.130 DEBUG 445.73 Event kernel.terminate->webprofiler has been notified.
Profiling
template
# Time (msec) Name Cached Took (msec)
1 3.541 docs.tpl.php 0 2.241