cookie-> getValue()导致FatalErrorException

时间:2014-03-29 18:56:47

标签: symfony cookies

我在前一个会话期间在javascript中设置了cookie。我可以通过Firebug看到cookie存在。但是,当我尝试在控制器代码中获取cookie值时,我得到致命错误。

代码:

public function indexAction()
{
        $request = Request::createFromGlobals();

        $cookies = $request->cookies;

        $cookieState = ($cookies->has('state') ? $cookies->get('state') : 0);
        $cookieLocationId = $cookies->has('locationId') ? $cookies->get('locationId') : 0;

        if (!$cookieState && !$cookieLocationId)
        {
            return array();
        }
        else
        {
            if($cookieLocationId)
            {
                $this->redirect($this->generateUrl('workoutexchange_wxexchange_default_location', array('locationId' => $cookieLocationId->getValue())));
            }

            $this->redirect($this->generateUrl('workoutexchange_wxexchange_default_state', array('state' => $cookieState->getValue())));
        }
}

结果错误:

FatalErrorException: Error: Call to a member function getValue() on a non-object in /opt/lampp/htdocs/workoutexchange/src/WorkoutExchange/WXExchangeBundle/Controller/DefaultController.php line 38

也许我没有正确检索过某些Cookie?

请帮我正确阅读cookies。

2 个答案:

答案 0 :(得分:1)

您可以将代码重写为:

public function indexAction(Request $request)
{
    $cookieState = $request->cookies->get('state', 0);
    $cookieLocationId = $request->cookies->get('locationId', 0);

    if (!$cookieState && !$cookieLocationId)
    {
        return array();
    }
    else
    {
        if($cookieLocationId)
        {
            $this->redirect($this->generateUrl('workoutexchange_wxexchange_default_location', array('locationId' => $cookieLocationId->getValue())));
        }

        $this->redirect($this->generateUrl('workoutexchange_wxexchange_default_state', array('state' => $cookieState->getValue())));
    }
}

它会更清洁,应该解决你的问题

不要忘记导入课程:

  

使用Symfony \ Component \ HttpFoundation \ Request;

享受!

答案 1 :(得分:0)

var_dump()救援......我发现$cookies->get('state')正在返回实际值,而不是cookie对象。