CakePHP Cache Config always reverts to File (from Memcache or APC) - cakephp

Firstly both Memcache and APC are installed successfully using PECL (and are verified as working) on my Macbook Pro dev server running PHP 5.3.15
I've just baked a test Cake 2.2.2 app. In Config/core.php I have the following:
/**
* Pick the caching engine to use. If APC is enabled use it.
* If running via cli - apc is disabled by default. ensure it's available and enabled in this case
*
*/
$engine = 'File';
if (extension_loaded('apc') && function_exists('apc_dec') && (php_sapi_name() !== 'cli' || ini_get('apc.enable_cli'))) {
$engine = 'Apc';
}
if (extension_loaded('memcache') && php_sapi_name() !== 'cli') {
$engine = 'Memcache';
}
// In development mode, caches should expire quickly.
$duration = '+999 days';
if (Configure::read('debug') >= 1) {
$duration = '+10 seconds';
}
// Prefix each application on the same server with a different string, to avoid Memcache and APC conflicts.
$prefix = 'mcmyapp_';
/**
* Configure the cache used for general framework caching. Path information,
* object listings, and translation cache files are stored with this configuration.
*/
Cache::config('_cake_core_', array(
'engine' => $engine,
'prefix' => $prefix . 'cake_core_',
'path' => CACHE . 'persistent' . DS,
'serialize' => ($engine === 'File'),
'duration' => $duration
));
/**
* Configure the cache for model and datasource caches. This cache configuration
* is used to store schema descriptions, and table listings in connections.
*/
Cache::config('_cake_model_', array(
'engine' => $engine,
'prefix' => $prefix . 'cake_model_',
'path' => CACHE . 'models' . DS,
'serialize' => ($engine === 'File'),
'duration' => $duration
));
Cache::config('default', array(
'engine' => $engine,
'serialize' => ($engine === 'File'),
'duration'=>$duration,
'prefix'=>$prefix,
));
debug(Cache::settings());
The output of the above final debug() is:
array(
'prefix' => '*****',
'engine' => 'Memcache',
'serialize' => false,
'duration' => (int) 10,
'servers' => array(
(int) 0 => '127.0.0.1'
),
'compress' => false,
'persistent' => true,
'probability' => (int) 100,
'groups' => array()
)
So in core.php it appears that Cake wants to use Memcache for its caching engine.
However, when I visit localhost/myapp/pages/home in my browser, CakePHP's default, freshly-baked welcome page greets me, informing me that The FileEngine is being used for core caching
Anywhere else in my app (other than in core.php) if I debug(Cache::settings()), I get the following:
array(
'prefix' => '*****',
'engine' => 'File',
'serialize' => false,
'duration' => (int) 10,
'servers' => array(
(int) 0 => '127.0.0.1'
),
'compress' => false,
'persistent' => true,
'probability' => (int) 100,
'groups' => array()
)
Basically, CakePHP appears to revert to File for caching, ignoring my configuration in core.php to use Memcache... unless I've done something wrong here??!
I've tried this with Configure::write('debug', 0) and Configure::write('debug', 1).
I should mention that with the above, both APC and Memcache extensions are enabled in php.ini.
Any help would be gratefully received, thanks in advance.

Memcached should be on some port, default one is 11211 (check)... So your config tries to connect to Memcached, fails and reverts back to default (File) cache...
Try:
Cache::config('default', array(
'engine' => 'Memcache',
'duration'=> 3600,
'probability'=> 100,
'servers' => array('127.0.0.1:11211') <<<<==
));

Related

How to decrease session time in cakephp

i have write this code in app/Config/core.php file of cakephp to timeout in 1 minute
Configure::write('Session', array(
'defaults' => 'php',
'timeout' => 1,
'autoRegenerate' => true
));
but this code not work
When you use the 'php' defaults, the time out is actually taken from the session.cookie_lifetime directive in php.ini. Either change the value in the php.ini configuration for your php or change the configuration like this:
Configure::write('Session', array(
'defaults' => 'php',
'autoRegenerate' => true,
'ini' => array('session.cookie_lifetime' => $timeInSeconds)
));

cakephp redis storage besides sessions

I am trying to use redis as my caching engine and I have so far was able to add the add redis in cakephp and it writes my sessions to my redis just fine. This is what I did in the core
$engine = 'Redis';
$prefix = 'myapp_';
Cache::config('session', array(
'engine' => $engine,
'prefix' => $prefix . 'cake_session_',
'duration' => $duration
));
Configure::write('Session', array(
'defaults' => 'cache',
'timeout' => 100,
'start' => true,
'checkAgent' => false,
'handler' => array(
'config' => 'session'
)
));
Now I want to be able to write to redis from my controller some cached queries but I am not able to save that in redis. Instead it saves it to some default (I have no idea where) cache.
This is what I did in my controller
public function index()
{
Cache::write("TestKey","myquery","default");
var_dump(Cache::read("TestKey")); die;
}
The above gives me the value myquery on the browser but when I go to my redis-cli and look for keys * I do not see that key there. So obviously its saving somewhere else. I am not sure how to make it to write to redis. I have tried this Cache::write("TestKey","myquery","Redis"); but that also did not work.
Thanks for help in advance
**EDIT 1 **
I just did some debugging and it looks like its trying to add to file
object(FileEngine)[3]
protected '_File' => null
public 'settings' =>
array (size=10)
'engine' => string 'File' (length=4)
'path' => string '/Library/WebServer/Documents/phoneapp_backend/app/tmp/cache/' (length=60)
'prefix' => string 'cake_' (length=5)
'lock' => boolean true
'serialize' => boolean true
'isWindows' => boolean false
'mask' => int 436
'duration' => int 3600
'probability' => int 100
'groups' =>
array (size=0)
empty
protected '_init' => boolean true
protected '_groupPrefix' => null
How do I change it to write to redis?
Thanks
You need to configure the default cache configuration to use Redis insteado of File. In app/Config/bootstrap.php Change
Cache::config('default', array('engine' => 'File'));
So it reads:
Cache::config('default', array('engine' => 'Redis'));
You may need to add more options to the configuration for specifying the server and port where Redis is running.

CakePHP: Cache can write file but not read it (always false)

I am trying to cache something. In my core.php config file, I have this:
//short
Cache::config('short', array(
'engine' => 'File',
'duration' => '+1 hours',
'path' => CACHE,
'prefix' => 'cake_short_'
));
// long
Cache::config('long', array(
'engine' => 'File',
'duration' => '+1 week',
'probability' => 100,
'path' => CACHE . 'long' . DS,
));
in my controller, I have this:
$xmlpublist = Cache::read('xmlpublist');
var_dump($xmlpublist);
//if cache is still set, return cache
if($xmlpublist !== false) {
die('cache A');
return $xmlpublist;
}
Cache::write('xmlpublist', "test", 'short');
die('cache C');
return $xml;
I can see that the file is generated - /path/to/cache/cake_short_xmlpublist
But when I Cache::read('xmlpublist'), I always get bool(false). I made sure that I have both read and write access to the cache directory.
Expectation:
Get values from the cache.
Result:
I get bool(false)
Where could have I gone wrong?
Any reply appreciated ;)
Thanks,
W
When calling Cache::read() you need to include the cache configuration to read from, so in your case 'short'. Without that additional parameter you'll be reading from the 'default' config which probably doesn't have the key you're looking for.

Different session timeouts for admin and users in CAKEPHP 2.0. is it possible?

I am using cakephp 2.0 for developing a website. Site will contain only 2 types of users. Admin and users(customers). now I need to set session time out 10 minutes for customer and 1 hour for admin. is it possible ?. My core.php file contains the line like this,
Configure::write('Session', array(
'defaults' => 'php',
'cookie' => 'xyz',
'timeout' => 10,
'checkAgent' => false,
));
It is more correct you do this condition in the AppController than to change your core.php this magnitude. You can make only this:
Configure::write('Session.timeout', 60);
And if you're using Acl, verify if user is admin using his own Acl method instead strripos.
I added the following lines in core.php file. For quick fix
if(strripos($_SERVER['REDIRECT_URL'],"admin/"))
{
Configure::write('Session', array(
'defaults' => 'php',
'cookie' => 'xyz',
'timeout' => 60,
'checkAgent' => false,
));
}
else
{
Configure::write('Session', array(
'defaults' => 'php',
'cookie' => 'xyz',
'timeout' => 10,
'checkAgent' => false,
));
}

How Can I Read the DB Configuration Settings From a Cake Shell?

I would like to write a cake shell to do a nightly backup of my database using mysqldump. I could do this as a shell script, but if I can cram it into a CakePHP shell, then I will get the added benefit of it working across both the development and live server, if I can get it to automagically read my database config settings. I will cron the cake shell and have some peace-of-mind knowing that I have frequent backups of my DB.
In my shell I'm trying to build up a string which starts with "mysqldump --user=" and I'd like to get the username from app/config/database.php. How can I get at the data in database.php?
In cake 2.1 the format has changed to:
App::uses('ConnectionManager', 'Model');
$dataSource = ConnectionManager::getDataSource('default');
$username = $dataSource->config['login'];
The following snippet should do the trick:
App::import('Core', 'ConnectionManager');
$dataSource = ConnectionManager::getDataSource('default');
$username = $dataSource->config['login'];
In CakePHP 3.x the format has changed to -
use Cake\Datasource\ConnectionManager;
$source = ConnectionManager::get('default');
debug($source); #Debugging the result
Result :
object(Cake\Database\Connection) {
'config' => [
'password' => '*****',
'username' => '*****',
'host' => '*****',
'database' => '*****',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'encoding' => 'utf8',
'timezone' => 'UTC',
'cacheMetadata' => true,
'quoteIdentifiers' => false,
'log' => false,
'url' => null,
'name' => 'remote'
],
'driver' => object(Cake\Database\Driver\Mysql) {
'connected' => false
},
'transactionLevel' => (int) 0,
'transactionStarted' => false,
'useSavePoints' => false,
'logQueries' => false,
'logger' => null
}
Get the Result :
debug($source->config()); #Accessing the result
Result :
[
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
'username' => 'username',
'password' => 'password',
'database' => 'database',
'encoding' => 'utf8',
'timezone' => 'UTC',
'cacheMetadata' => true,
'quoteIdentifiers' => false,
'log' => false,
'url' => null,
'name' => 'remote'
]
Just for sharing.
For any cakephp project, if using php as cronjob or command line to do large data processing I would build a standalone php script without cakephp, the reason for doing this because cakephp is slow (e.g. read & process 100K records).
To make my life simple I put all my standalone scripts under app/Vendor/myscripts/ (e.g: app/Vendor/myscripts/process.php)
below also the basic code to make sure you use the same database settings in standalone script with cakephp (tested with MySQL)
require_once '/XYZ/app/Config/database.php';
$database = new DATABASE_CONFIG;
try{
$dblink = new PDO('mysql:host='.$database->default['host'].';dbname='.$database->default['database'], $database->default['login'], $database->default['password'], array(PDO::ATTR_PERSISTENT => false));
$dblink->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dblink->exec('SET CHARACTER SET '.$database->default['encoding']);
} catch (Exception $e) {
die('DB Error'. $e->getMessage());
}
Example in controller, Change multi DB for DataSources in CakePHP 2.5.x
App::uses('AppController', 'Controller');
class DemoController extends AppController {
public $uses = array('AppModel', 'GVA21', 'GVA01', 'GVA14', 'GVA24' );
public function test_dbs(){
$this->autoRender=false;
// Load ConnectManager
App::uses('ConnectionManager', 'Model');
// DataSource ['default']
$MDM = $this->GVA14->find('count');
echo "MDM.GVA14\n<br>";
debug($MDM);
// Get DataSource Config DB ['default'] and ['SRL']
$confDeafult = ConnectionManager::$config->default;
$confSrl = ConnectionManager::$config->SRL;
// Change DataSource ['SRL']
ConnectionManager::drop('default');
ConnectionManager::create('default',$confSrl); //<== Is permanet change Find All models Down
// $this->GVA01->setDataSource('SRL'); //<== Is temp change Find model
echo "SRL.GVA14\n<br>";
$SRL = $this->GVA14->find('count');
debug($SRL);
$SRL = $this->GVA01->find('count');
echo "SRL.GVA01\n<br>";
debug($SRL);
$SRL = $this->GVA21->find('count');
echo "SRL.GVA21\n<br>";
debug($SRL);
// Change to DataSource ['default']
debug(ConnectionManager::drop('default'));
ConnectionManager::create('default',$confDeafult); //<== Is permanet change Find All models Down
//$this->GVA01->setDataSource('default'); //<== Is temp change Find model
$MDM = $this->GVA01->find('count');
echo "MDM.GVA01\n<br>";
debug($MDM);
$MDM = $this->GVA21->find('count');
echo "MDM.GVA21\n<br>";
debug($MDM);
////FIN
exit('FIN');
}

Resources