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

I can not call the service from DI

    // services.php
    $di->setShared('translation', function () use ($config) {
        $language = 'ru';

        // Проверка существования перевода для полученного языка
        if (file_exists($config->application->translationDir.$language.".php")) {
            require_once ($config->application->translationDir.$language.".php");
        } else {
            // Переключение на язык по умолчанию
            require_once ($config->application->translationDir.$language."/ru.php");
        }

        // Возвращение объекта работы с переводом
        return new Phalcon\Translate\Adapter\NativeArray(array(
            "content" => $messages
        ));
    });
    // someTask.php
    class someTask extends Phalcon\CLI\Task {

        public function someAction() {
            ...
            // not work
            $subject = $this->getDI()->get('translation')->_('subject');

            // not work
            $subject = $this->di->getShared('translation')->_('subject');

            // not work
            $subject = $this->getTranslation->_('subject');
            ...
        }
    }

Result: Service 'translation' wasn't found in the dependency injection container

I can not call the service "translation" from DI.

Help me, pls!



14.3k

Phalcon 2.0.4



4.0k
edited Jul '15
  1. how do you call this task?
  2. Show your Bootstrap


5.7k

Along with the two things @Paulius asked for, have you tried these two things?

Instead of $di->setShared, try using $di->set

    // services.php
    $di->set('translation', function () use ($config) {
        $language = 'ru';

        // Проверка существования перевода для полученного языка
        if (file_exists($config->application->translationDir.$language.".php")) {
            require_once ($config->application->translationDir.$language.".php");
        } else {
            // Переключение на язык по умолчанию
            require_once ($config->application->translationDir.$language."/ru.php");
        }

        // Возвращение объекта работы с переводом
        return new Phalcon\Translate\Adapter\NativeArray(array(
            "content" => $messages
        ));
    });

and for calling the service:

    // someTask.php
    class someTask extends Phalcon\CLI\Task {

        public function someAction() {
            ...
            $subject = $this->getDI()->getTranslation();
            ...
        }
    }

Just a few things to rule out.



4.0k
Accepted
answer

Try:

$this->getDI()->get('translation')->_('Hello!');
//or
$this->getDI()->getShared('translation')->_('Hello!');
//or
$this->translation->_('Hello!');

My tested example below.

ru.php

<?php
return array (
    'Hello!' => 'Привет!'
);

SomeTask.php

<?php

class SomeTask extends Phalcon\CLI\Task {

    public function someAction() {
        var_dump($this->getDI()->get('translation')->_('Hello!'));
        var_dump($this->getDI()->getShared('translation')->_('Hello!'));
        var_dump($this->translation->_('Hello!'));
    }
}

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'
    )
);
$loader->register();

$di->setShared('translation', function () {
    return new Phalcon\Translate\Adapter\NativeArray(array(
        "content" => require APPLICATION_PATH.'/langs/ru.php',
    ));
});

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

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

// 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);
}

And run:

$ php cli.php Some some
string(13) "Привет!"
string(13) "Привет!"
string(13) "Привет!"

Is there a way to call another Shared service like in this example

$this->translation->_('Hello!');

i.e.

$this->mySharedService->_(array(1,2,3));