Reputation: 158
I've been playing with the Phalcon framework for some time now, but I haven't managed to figure out how to work with application events (via the EventManager).
Specifically, I would like to create a 'boot' event, so I can run code only once per application instead of once per controller (which would be the case if I extended a ControllerBase).
The manual gives me the syntax to use, but I still don't know how to use it and in what file I should put it.
I know I could just require a 'boot.php' file in index.php, but that isn't really an elegant solution.
Upvotes: 1
Views: 1963
Reputation: 11485
Assume that you have the index.php
file which is the entry point of your application. In that file you have code to register all the services in your application. My personal preference is to keep the index.php
file as small as possible and put the bootstrap sequence (registering services) in a different file.
So I would have in the index.php
<?php
use \Phalcon\DI\FactoryDefault as PhDi;
error_reporting(E_ALL);
date_default_timezone_set('US/Eastern');
if (!defined('ROOT_PATH')) {
define('ROOT_PATH', dirname(dirname(__FILE__)));
}
try {
include ROOT_PATH . "/app/var/bootstrap.php";
/**
* Handle the request
*/
$di = new PhDi();
$app = new Bootstrap($di);
echo $app->run(array());
} catch (\Phalcon\Exception $e) {
echo $e->getMessage();
} catch (PDOException $e){
echo $e->getMessage();
}
The bootstrap.php contains the functions needed to initialize all the services that your application needs. One of these services can be as follows:
public function initEventsManager($app)
{
$evManager = new \Phalcon\Events\Manager();
$app->setEventsManager($evManager);
$evManager->attach(
"application",
function($event, $application) {
switch ($event->getType()) {
case 'boot':
$this->handleBoot();
break;
case 'beforeStartModule':
$this->handleBeforeStartModule();
break;
case 'afterStartModule':
$this->handleAfterStartModule();
break;
case 'beforeHandleRequest':
$this->handleBeforeHandleRequest();
break;
case 'afterHandleRequest':
$this->handleAfterHandleRequest();
break;
}
);
}
In your bootstrap.php
file you should have relevant functions such as handleBoot
handleAfterHandleRequest
etc. that will process the code the way you need to.
The above function to register the events manager will need to be invoked with the Phalcon\Mvc\Application as a parameter. A good place to put it would be here (based on the examples)
https://github.com/phalcon/website/blob/master/app/var/bootstrap.php#L62
Upvotes: 3