Search code examples
cachingyiiyii2apc

Yii2 - Use APC cache from console


I am trying to make console command to add data to the APC cache, but so far without any success.

This code works perfectly when I run it as a standard action (controller/action):

    public function actionUpdateExchangeRate()
    {

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL            => 'https://openexchangerates.org/api/latest.json?app_id=xxxxxxx',
            CURLOPT_USERAGENT      => 'Exchange Rates'
        ));

        $json = curl_exec($curl);

        curl_close($curl);

        $rates = json_decode($json);

        Yii::$app->cache->set('rates', $rates->rates);

    }

I made a command with the same code, and when I try to set the cache, nothing is happening.

var_dump('<pre>', Yii::$app->cache->set('rates', $rates->rates), '</pre>');die;

Dump give true when run as a controler/action, and false when run from the command.

In the console.php I added this configuration to the component (it is same in the web.php):

    'cache' => [
        'class'     => 'yii\caching\ApcCache',
        'keyPrefix' => 'test',
        'useApcu'   => true
    ],

PHP version is:

PHP 7.2.4-1+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Apr  5 2018 08:53:57) ( NTS )

Any idea what I am doing wrong here?


Solution

  • Make sure that you have enabled apc.enable_cli in php.ini.

    But using ApcCache for console does not make much sense. APCu cache is per process, so it will be removed anyway after command is ended and console commands will not share cache with web requests.

    Mostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Under normal circumstances, it is not ideal to create, populate and destroy the APC cache on every CLI request, but for various test scenarios it is useful to be able to enable APC for the CLI version of PHP easily.

    https://secure.php.net/manual/en/apcu.configuration.php#ini.apcu.enable-cli