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

How do I access dependency injection in \Phalcon\CLI\Task?

I'm following the command line application (written in the docs) closely, and manage to run simple cli application. However, when I re-look at the dependency injection, I have no clues how to access the dependency which has been injected.

Any ideas?

Code in details: https://docs.phalcon.io/en/latest/reference/cli.html#creating-a-bootstrap

// Load the configuration file (if any) if(is_readable(APPLICATION_PATH . '/config/config.php')) { $config = include APPLICATION_PATH . '/config/config.php'; $di->set('config', $config); }

What to do in order to access the $config set in the cli bootstrap from the mainTask controller?



3.7k

Here is the solution I have right now, but I not sure is this recommended :

class mainTask extends \Phalcon\CLI\Task implements \Phalcon\DI\InjectionAwareInterface { protected $_di;

/**
 * setter for dependency injection
 */
public function setDi($di)
{
    $this->_di = $di;
}

/**
 * getter for dependency injection
 */
public function getDi()
{
    return $this->_di;
}

public function indexAction()
{
  $config = $this->_di->get("config");
}

}

It's normal if you wil create Abstract task and move $_di into it... and will get it through getDI() method.

edited Oct '14

Hi..

I have a similer question.

I have injected a service under my cli.php called beanstalk and extending \Phalcon\CLI\Task perfectly.

My question is as per doc (https://docs.phalcon.io/en/latest/api/Phalcon_CLI_Task.html), Phalcon\CLI\Task extends Phalcon\DI\Injectable and implements Phalcon\Events\EventsAwareInterface, Phalcon\DI\InjectionAwareInterface so why i am not getting my service if i am calling $this->getDI(''beanstalk). As per doc, \Phalcon\CLI\Task is already having a method called getDI through which i can get my service.

cli.php

<?php

use Phalcon\DI\FactoryDefault\CLI as CliDI,
    Phalcon\CLI\Console as ConsoleApp;

define('VERSION', '1.0.0');

//Using the CLI factory default services container
$di = new CliDI();

// Define path to application directory
defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__)));

/**
 * Register the autoloader and tell it to register the tasks directory
 */
$loader = new \Phalcon\Loader();
$loader->registerDirs(
        array(
            APPLICATION_PATH . '/tasks',
            APPLICATION_PATH . '/models'
        )
);
$loader->register();

// Load the configuration file (if any)
if (is_readable(APPLICATION_PATH . '/config/config.php')) {
    $config = include APPLICATION_PATH . '/config/config.php';
    $di->set('config', $config);
}

$config = $di->get('config');

//Setup the database service
    $di->set('db', function() use ($config) {
        return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
            "host" => $config->database->host,
            "username" => $config->database->username,
            "password" => $config->database->password,
            "dbname" => $config->database->dbname
        ));
    });

//Setup the beanstalk service
    $di->set('beanstalk', function() use ($config) {
        return new \Phalcon\Queue\Beanstalk(array(
            "host" => $config->beanstalk->host,
            "port" => $config->beanstalk->port            
        ));
    });

//Create a console application
$console = new ConsoleApp();
$console->setDI($di);

/**
 * Process the console arguments
 */
$arguments = array();
$params = array();

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

// define global constants for the current task and action
define('CURRENT_TASK', (isset($argv[1]) ? $argv[1] : null));
define('CURRENT_ACTION', (isset($argv[2]) ? $argv[2] : null));

try {
    // handle incoming arguments
    $console->handle($arguments);
} catch (\Phalcon\Exception $e) {
    echo $e->getMessage();
    exit(255);
}

MainTask.php

<?php

class mainTask extends \Phalcon\CLI\Task {

    public function mainAction() {
        echo "\nThis is the default task and the default action \n";
    }

    /**
     * @param array $params
     */
    public function testAction() {
        $users = Users::find();
        if($users)
        {
            foreach($users as $user)
            {
                echo $user->name . '-' . $user->email . PHP_EOL;
            }
        }
    }

    public function consumerAction() {
        // Get Beanstalk Service
        $queue = $this->getDI('beanstalk');

        while (($job = $queue->peekReady()) !== false) {

            $job = $queue->reserve();

            $message = $job->getBody();

            var_dump($message);

            $job->delete();
        }
    }

    public function producerAction() {
        // Get Beanstalk Service
        $queue = $this->getDI('beanstalk');

        //Insert the job in the queue with options
        $jobId = $queue->put(
                array('processVideo' => 4871)
        );
        echo $jobId . PHP_EOL;
    }

    public function checkAction() {
        // Get Beanstalk Service
        $queue = $this->getDI('beanstalk');

        //echo 'hello' . PHP_EOL;
    }

}

Please suggest.

Note: If i am using suggested solution provided by @ajreal than i am getting my service (beanstalk) perfectly.

Thanks in advance.

Thanks & Regards Tapan Thapa

edited Oct '14

Hi,

I am sorry if i am asking huge help here however i am just jumping into phalconphp and was using codeigniter,laravel 4 and symfony in past.

Here is the new MainTask.php which is working fine. Let me know if i am doing anything wrong here as i need performance no matter what.

<?php

class mainTask extends \Phalcon\CLI\Task {

    public function mainAction() {
        echo "\nThis is the default task and the default action \n";
    }

    protected $di;

    public function initialize()
    {
        $this->di = $this->getDI();
    }

    /**
     * @param array $params
     */
    public function testAction() {
        $users = Users::find();
        if($users)
        {
            foreach($users as $user)
            {
                echo $user->name . '-' . $user->email . PHP_EOL;
            }
        }
    }

    public function consumerAction() {
        // Get Beanstalk Service
        $queue = $this->di->get('beanstalk');

        while (($job = $queue->peekReady()) !== false) {

            $job = $queue->reserve();

            $message = $job->getBody();

            var_dump($message);

            $job->delete();
        }
    }

    public function producerAction() {
        // Get Beanstalk Service        
        $queue = $this->di->get('beanstalk');

        //Insert the job in the queue with options
        $jobId = $queue->put(
                array('processVideo' => 4871)
        );
        echo $jobId . PHP_EOL;
    }

    public function checkAction() {
        // Get Beanstalk Service
        $queue = $this->di->get('beanstalk');

        //echo 'hello' . PHP_EOL;
    }

}

Thanks & Regards Tapan Thapa