Hello!
I have CLI Task and i need to work with cache.
UPD: It's strange that Apc handler works bad (always NULL), but Memcache handler working well.
GitHub issue: https://github.com/phalcon/cphalcon/issues/3269
I'm using di like that:
MainTask.php
use Phalcon\CLI\Task;
/**
* Class MainTask
*
* @property \Phalcon\DI\FactoryDefault\CLI $di
* @property \Phalcon\Cache\Multiple $cache
*/
class MainTask extends Task
{
protected $di;
protected $cache;
public function mainAction()
{
echo "\n\tUsage: $ php cli.php [task] [action] [args ...]\n\n";
echo "\tAvaiable tasks:\n";
echo "\t\t– cache\n";
}
public function initialize()
{
$this->di = $this->getDI();
$this->cache = $this->di->getShared('cache');
}
}
CacheTask.php
use Api\Models\Users;
class CacheTask extends MainTask
{
public function mainAction()
{
echo "\n\tUsage: $ php cli.php generate [action] [args ...]\n\n";
echo "\tAvaiable tasks:\n";
echo "\t\t– users\n";
}
public function usersAction()
{
$id = 42;
$key = "Users_$id";
$user = Users::findFirst($id);
$userArr = $user->toArray();
$userArr['foobar'] = $user->calculateSomeData();
$this->cache->save($key, $userArr);
$userCached = $this->cache->get($key);
var_export($id); echo "\n"; // [ OK ]: 42
var_export($key); echo "\n"; // [ OK ]: "Users_42"
var_export($userArr); echo "\n"; // [ OK ]: array(/* ... */)
var_export($userCached); echo "\n"; // [FAIL]: NULL
}
}
Why $userCached is always null? Any data NOT write in cache.
services config
use Phalcon\Cache\Backend\Apc;
use Phalcon\Cache\Backend\Memcache;
use Phalcon\Cache\Frontend\Data;
use Phalcon\Cache\Multiple;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\DI\FactoryDefault as ServerDI;
use Phalcon\DI\FactoryDefault\CLI as CliDI;
// List of all services
$serviceConfig = $config;
$serviceCache = function () use ($serviceConfig) {
$frontend = new Data($serviceConfig->cache->frontend->toArray());
return new Multiple(array(
// With APC test FAILS, $userCached == NULL
new Apc($frontend, $serviceConfig->cache->apc->toArray()),
// With Memcached everithing ok OK, $userCached == array(/**/)
// new Memcache($frontend, $serviceConfig->cache->memcache->toArray()),
));
};
$serviceDb = function () use ($serviceConfig) {
return new DbAdapter($serviceConfig->db->toArray());
};
// Config
$sConfig = array(
'cli' => array(
'cache' => $serviceCache,
'config' => $serviceConfig,
'db' => $serviceDb,
),
'server' => array(
'cache' => $serviceCache,
'config' => $serviceConfig,
'db' => $serviceDb,
),
);
// Load!
if (php_sapi_name() != 'cli') {
$sLoadType = 'server';
$di = new ServerDI();
}
else {
$sLoadType = 'cli';
$di = new CliDI();
}
foreach ($sConfig[$sLoadType] as $sName => $sCallback)
$di->setShared($sName, $sCallback);