We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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.



4.0k

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 !