Cakephp3 Change cache duration in controller - caching

Hello everyone I work with cakephp3 here is my cache configuration in app.php
'Cache' => [
'access_token' => [
'className' => 'File',
'duration' => '+2 minutes',
'path' => CACHE
]
],
I set the duration to 2 minutes but I need to dynamically change the duration via my Controller.
I I tried setConfig but it does not work
Cache::write("access_token_$key", $response, 'access_token');
Cache::setConfig("access_token_$key", array('duration' => $time));
Also i tried this but still does not work
$engine = Cache::engine("access_token_$key");
$engine->config("duration", $time);
Thanks for any help

Related

yii2 pagecahe array dependecny

I am implementing page cache for one of my page. For depenedency, I have to check an array, which can be either exist or not. Possible array keys cane ,
usersearch['id'], usersearch['name'], usersearch['phone]. I have to add dependency for any change in these values as well.
Also, I have to clear cache for any update or add in user table.
Is there any possible solution for this.?
Thanks in advance
You can use variations
public function behaviors(){
$usersearch = Yii::$app->requst->get('usersearch');
return [
[
'class' => 'yii\filters\PageCache',
'only' => ['index'],
'duration' => 60,
'variations' => [
'YOUR_DYNAMIC_VALUE1','YOUR_DYNAMIC_VALUE2'
],
'dependency' => [
'class' => 'yii\caching\DbDependency',
'sql' => 'SELECT COUNT(*) FROM post',
],
],
];
}
Ref link
IN YOUR CASE ,you can use
'variations' => \Yii::$app->requst->get('usersearch')??[],
or
'variations' => [
\/Yii::$app->requst->get('usersearch')['id'] ?? '',
\Yii::$app->requst->get('usersearch')['name'] ?? '',
\Yii::$app->requst->get('usersearch')['phone'] ?? '',
]
You could use a yii\caching\FileCache component with the following configuration.
Firstly, you set the cache in the init function of your controller:
Yii::$app->setComponents([
'yourCacheName' => [
'class' => \yii\caching\FileCache::class,
'defaultDuration' => 1800, //cache duration in seconds
'keyPrefix' => Yii::$app->getSession()->getId(). '_'
]
]);
Here, the parameter keyPrefix is set so that it is linked to the session ID. Thus, the visitors do not see each other's cached page. If the content is static and equal, regardless of the user or the session, this parameter can be removed.
In the view that must be cached you can call the beginCache function and the dependency as follows:
$this->beginCache('cache-id', [
'cache' => Yii::$app->yourCacheName, // the name of the component as set before
'variations' => [
$usersearch['id'] ?? '',
$usersearch['name'] ?? '',
$usersearch['phone'] ?? '',
],
'dependency' => [
'class' => \yii\caching\DbDependency::class,
'sql' => 'SELECT count(*) FROM your_user_table'
]
]);
// your view
$this->endCache();

how to stop execution of ctp file in cakephp 2.x after validating the url

In my CakePHP application, I have applied Url validations so that admin can access only those actions which are defined for admin and same as with users.
In my application, "surveylist" is the action of admin and when any user directly access that action(surveylist), URL validations work(Unauthorized access msg is displayed).
But below that message ctp file of surveylist executes forcefully and show errors because I have validated URL through the try-catch block and it cannot get the set variables of action.
I want that ctp file should not execute if unauthorize error comes.
My code for surveylist is:-
public function surveylist($pg=null){
try{
if($this->checkPageAccess($this->params['controller'] . '/' . $this->params['action'])){
$this->Paginator->settings = array(
'Survey' => array(
'limit' => 5,
'order' => 'created desc',
'conditions'=>array('is_deleted'=> 0),
'page' => $pg
)
);
$numbers = $this->Paginator->paginate('Survey');
$this->set(compact('numbers'));
}else{
$this->Flash->set(__('Unauthorised access'));
}
}catch(Exception $e){
$this->Flash->set(__($e->getMessage()));
}
}
I don't want the ctp file of surveylist to execute if control comes to else.
Plz, help me out......
Thanx in advance...
I suppose you are using prefix to separate admin and users, if not please do that it is great way to handle and restrict methods.
After doing that you have to make condition to check which prefix(admin, user) is currently active and according that load Auth component and allow action in allow() method of Auth.
Example:
$this->loadComponent('Auth',[
/*'authorize' => [
'Acl.Actions' => ['actionPath' => 'controllers/']
],*/
'loginRedirect' => [
'controller' => 'Users',
'action' => 'index'
],
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'unauthorizedRedirect' => [
'controller' => 'Users',
'action' => 'login',
'prefix' => false
],
'authError' => 'You are not authorized to access that location.',
]);
if ($this->request->params['prefix']=='admin') {
// Put actions you want to access to admin in allow method's array
$this->Auth->allow(array('add', 'edit', etc...));
} else if ($this->request->params['prefix']=='user') {
// Put actions you want to access to user in allow method's array
$this->Auth->allow(array('login', 'view', etc...));
}
This way you can restrict actions for particular role.
Hope this helps!

Yii2 session expires after user is idle for a fixed seconds despite session timeouts being set to at least 1 day

I have already added these codes in my config/web file
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
'enableSession' => true,
'authTimeout' =>86400,
'loginUrl' => ['account/login'],
],
'session' => [
'timeout' => 86400,
],
After session expires I want to automatically logout and redirect to login action.
Make sure in your php.ini file
config
session.gc_maxlifetime
by default set as :
session.gc_maxlifetime=1440
change it, to :
session.gc_maxlifetime=86400
Very first you have to set 'enableAutoLogin' => false, .
now add these lines there in your config/web.
I have added it in frontend/config/main.php because I am using frontend only.
'components' => [
...
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => false,
'enableSession' => true,
'authTimeout' => 1800, //30 minutes
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'class' => 'yii\web\Session',
'name' => 'advanced-frontend',
'timeout' => 1800,
],
...
Now go to yii2/web/User.php and write code for destroy session in logout method before return as guest()-
public function logout($destroySession = true)
{
$identity = $this->getIdentity();
if ($identity !== null && $this->beforeLogout($identity)) {
......
if ($destroySession && $this->enableSession) {
Yii::$app->getSession()->destroy();
}
$this->afterLogout($identity);
}
$session = Yii::$app->session;
$session->remove('other.id');
$session->remove('other.name');
// (or) if is optional if above won't works
unset($_SESSION['class.id']);
unset($_SESSION['class.name']);
// (or) if is optional if above won't works
unset($session['other.id']);
unset($session['other.name']);
return $this->getIsGuest();
}
For me it worked great.

Installing user-management for Yii2.0

I've been trying to install user-management for Yii2.0, but getting ReflectionException while loading the page. I have attached the error page and directory structure below.
and the file path is as shown below.
I've searched a lot to find out the reason for this, but nothing worked out. can someone tell me what am I missing here to get it work. looks like the user-management installation documentation has some flaws. It is not clear enough to understand. Hope to get the steps to install. Thanks
Here is my console/web.php
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'gAry7SfUr0oOjNQDqItsobmGBcJajQoW',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
//'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
'class' => 'app\webvimark\modules\user-management\components\UserConfig',
// Comment this if you don't want to record user logins
'on afterLogin' => function($event) {
\webvimark\modules\user-management\models\UserVisitLog::newVisitor($event->identity->id);
}
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
],
'modules'=>[
'user-management' => [
'class' => 'webvimark\modules\user-management\UserManagementModule',
// 'enableRegistration' => true,
// Here you can set your handler to change layout for any controller or action
// Tip: you can use this event in any module
'on beforeAction'=>function(yii\base\ActionEvent $event) {
if ( $event->action->uniqueId == 'user-management/auth/login' )
{
$event->action->controller->layout = 'loginLayout.php';
};
},
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
It seems to have a slight difference with the expected configuration for this extension.
Use this
'class' => 'webvimark\modules\UserManagement\components\UserConfig',
ie UserManagement instead of user-management is a configuration path and not a route

CakePHP 3 cell_cache configuration

I have the following code:
$cell = $this->cell('Admin/Notifications', ['since' => $user['last_login']], [
'cache' => ['config' => 'cell_cache', 'key' => 'notifications_' . $user['id']]
]);
echo $cell;
That i use to call a cell in CakePHP 3 and cache it at the same time. But it outputs an error:
Warning (512): Could not render cell - The "cell_cache" cache configuration does not exist. [CORE\src\View\Cell.php, line 244]
What am I missing? I have searched the manual but have not found if i must declare this configuration and where.
Thank you up front for your answers.
I have found the answer. In "config/app.php" I have added the following code to the "Cache" adapters:
'cell_cache' => [
'className' => 'File',
'prefix' => 'myapp_cell_cache_',
'path' => CACHE . 'persistent/',
'serialize' => true,
'duration' => '+10 minutes',
],
So it was something I have missed to configure, but it is not specified in the docs. I think it should be added.

Resources