Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Why nothing happens while using events (Phalcon 3 + PHP 7)

Hello,

Please consider this script :

<?php

use Phalcon\Di\FactoryDefault\Cli as CliDi;
use Phalcon\Cli\Console as ConsoleApp;

define('APP_DIR', __DIR__);
define('ROOT_DIR', APP_DIR . '/..');
define('PLUGINS_DIR', ROOT_DIR . '/plugins');

/**
 * Read the services
 */
$di = new CliDi();

/**
 * Include Services
 */
include __DIR__ . '/config/services.php';

/**
 * Call the autoloader service.  We don't need to keep the results.
 */
$di->getLoader();

/**
 * Get the configuration
 */
//$config = $di->getConfig();

// extra
$di['eventsManager']->attach('console:boot', function($event, $console) {
    var_dump('test');
});

/**
 * Create a console application
 */
$console = new ConsoleApp($di);

/**
 * Process the console arguments
 */
$arguments = [];

foreach ($argv as $k => $arg) {
    if ($k == 1) {
        $arguments['task'] = $arg;
    } elseif ($k == 2) {
        $arguments['action'] = $arg;
    } elseif ($k >= 3) {
        $arguments['params'][] = $arg;
    }
}

try {

    /**
     * Handle
     */
    $console->handle($arguments);
    echo PHP_EOL;
} catch (Exception $e) {
    echo $e->getMessage() . PHP_EOL;
    echo $e->getTraceAsString();
    echo PHP_EOL;
    exit(255);
}

Does anyone knows why the god 'test' is never displayed ? Script seems to never enter in my function.

Please help me.



46.7k
Accepted
answer
edited Aug '16

I think that you need to add the following line after you create the Console object but before you call handle:

$console->addEventManager($di->getEventsManager());

There can be a global events manager or you can choose to create an events manager for each object. This allows you to weigh the performance benefit of creating a new object versus having the event manager pass an event to all objects.



1.1k

Hi,

Thanks for your reply :)

I found another way to do what I wanted to do without using event system, but I even though tried your solution. Just after Phalcon\Console instanciation I wrote :

$console->setEventsManager($di->getEventsManager());

then my listener was well recognized (and "test" string was displayed !)

I was being misled by the fact that Phalcon\Console inherits from Phalcon\Injectable through Phalcon\Application. As Dependency Injector contains the eventsManager service, I thought that Console and eventsManager service were naturally connected since Console is an Injectable, but I was wrong : as you answered me, developer has to manually set an EventManager in Console instance.

Thanks for your reply !



46.7k

If everything that could possibly listen to events was always fully hooked up then it would needlessly slow the system down.