/** * Loads UserPreferences model from session or creates new one * @return UserPreferences */ public static function preferences() { if (static::$_cachedPreferences === null) { $model = new UserPreferences(); $model->load([]); $model->validate(); $attributes = Yii::$app->session->get('UserPreferencesModel'); if (isset($attributes) === true) { $model->setAttributes($attributes); } static::$_cachedPreferences = $model; } return static::$_cachedPreferences; }
public function bootstrap($app) { $app->on(Application::EVENT_AFTER_REQUEST, function () use($app) { $preferences = UserPreferences::preferences(); $defaultPreferences = new UserPreferences(); $defaultPreferences->load([]); $defaultPreferences->validate(); // compare current preferences with default // if user hasn't changed anything - don't flood session variable with default preferences if (count(array_diff($preferences->getAttributes(), $defaultPreferences->getAttributes())) !== 0) { $app->session->set('UserPreferencesModel', $preferences->getAttributes()); } else { $app->session->set('UserPreferencesModel', null); } }); $app->on(Application::EVENT_BEFORE_ACTION, function () use($app) { UserPreferences::preferences(); }); }