Yii - Manipulating a sesssion variable

2019-03-03 14:41发布

I am a still a newbie when it comes to using YII, but I been working with session variables for the past few days, and I can't seem to grasp to the concept behind my error. Any advice will be appreciated.

My add function works perfectly so far, for my current purpose of keeping track of the last 3 variables added to my session variable nutrition.

public function addSessionFavourite($pageId)
{
    $page = Page::model()->findByPk($pageId);
    $categoryName = $page->getCategoryNames();

    if($categoryName[0] == 'Nutrition')
    {
        if(!isset(Yii::app()->session['nutrition']))
        {
            Yii::app()->session['nutrition'] = array();
        }
        $nutrition = Yii::app()->session['nutrition'];
        array_unshift($nutrition, $pageId);
        array_splice($nutrition, 3);
        Yii::app()->session['nutrition'] = $nutrition;
    }

My remove function doesn't seem to work at all, no matter what I try to do with it. The reason why I am transfering the session array to a temp array was to try to get around the "If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called." But it was a total failure.

public function removeSessionFavourite($pageId)
{
    $page = Page::model()->findByPk($pageId);
    $categoryName = $page->getCategoryNames();

    if($categoryName[0] == 'Nutrition')
    {
        if(!isset(Yii::app()->session['nutrition']))
        {
            return true;
        }
        $nutritionArray = Yii::app()->session['nutrition'];
        unset($nutritionArray[$pageId]);
        Yii::app()->session['nutrition'] = $nutritionArray;
    }

Any advice or push toward to the correct direction will be appreciated.

1条回答
混吃等死
2楼-- · 2019-03-03 15:28

I personally I have never used Yii::app()->session I normally use the Yii user and I have never had any issues with it:

Yii::app()->user->setState('test', array('a'=>1,'b'=>2));
print_r(Yii::app()->user->getState('test')); //see whole array

$test = Yii::app()->user->getState('test');
unset($test['b']);
Yii::app()->user->setState('test',$test);
print_r(Yii::app()->user->getState('test')); //only 'a'=>1 remains

Yii::app()->user->setState('test', null);
print_r(Yii::app()->user->getState('test')); //now a null value

As I put in a comment above there seems to be issues with multidimensional arrays with the session variable: https://code.google.com/p/yii/issues/detail?id=1681

查看更多
登录 后发表回答