PHP code example of yii2tech / model-change
1. Go to this page and download the library: Download yii2tech/model-change library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
yii2tech / model-change example snippets
class PageController extends \yii\web\Controller
{
public function behaviors()
{
return [
'modelChange' => [
'class' => ModelChangeFilter::className(),
'except' => [
'index',
'view'
],
'modelClasses' => [
'app\models\Page'
],
'afterModelChange' => function ($event) {
Yii::$app->getSession()->set('cacheFlushRequired', true);
},
],
];
}
// ...
}
if (Yii::$app->session->get('cacheFlushRequired', false)) :
class MaintenanceController extends \yii\web\Controller
{
public function actionFlushCache()
{
Yii::$app->cache->flush();
Yii::$app->getSession()->remove('cacheFlushRequired');
return $this->redirect(['index']);
}
}
return [
'as modelChange' => [
'class' => 'yii2tech\modelchange\ModelChangeFilter',
'modelClasses' => [
'app\models\Page',
'app\models\PageContent',
'app\models\MenuItem',
],
'afterModelChange' => function ($event) {
Yii::$app->getSession()->set('cacheFlushRequired', true);
},
],
// ...
];
use yii2tech\modelchange\ModelChangeFilter;
use yii\base\Behavior;
class ModelChangeLogBehavior extends Behavior
{
public function events()
{
return [
ModelChangeFilter::EVENT_AFTER_MODEL_CHANGE => 'afterModelChange'
];
}
public function afterModelChange(ActionEvent $event)
{
$logMessage = 'modelId=' . $event->model->id . ' actionId=' . $event->action->id;
Yii::info($logMessage);
}
}
class PageController extends \yii\web\Controller
{
public function behaviors()
{
return [
'modelChange' => [
'class' => ModelChangeFilter::className(),
'modelClasses' => [
'app\models\Page'
],
],
'modelChangeLog' => [
'class' => ModelChangeLogBehavior::className(),
],
];
}
// ...
}
class PageController extends \yii\web\Controller
{
use ModelChangeTrait;
protected function defaultModelClasses()
{
return [
'app\models\Page'
];
}
public function beforeAction($action)
{
$this->attachModelEventListeners();
return parent::beforeAction($action);
}
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
$this->detachModelEventListeners();
return $result;
}
protected function afterModelChange($event)
{
// handle model change
}
}