如何在symfony2中的视图中获取会话变量

时间:2013-05-21 11:39:26

标签: symfony

感谢您的宝贵建议

我创建了一个登录系统,我想在会话变量

中存储用户的id

这是我的登录系统控制器

use Symfony\Component\HttpFoundation\Session\Session;

class successController extends Controller
{

public function successAction(Request $request)
    {

       --some code for form--
       $repository = $em->getRepository('RepairStoreBundle:users');
        $query = $repository->auth($name,$password);
      $error="sorry invalid username or password";   
           if($query== false)
            {
                return $this->render('RepairLoginBundle:login:login.html.php', array(
            'form' => $form->createView(),'error'=>$error,)); 
                }
        else
        {
            $role=$query[0]['role'];
            $id=$query[0]['id'];
            if($role == 1)
            {
                $session = new Session();
                $session->start();
                $session->set('id',$id);
                $result=$repository->display();
            return $this->render('RepairLoginBundle:login:success.html.php',array('result'=>$result,));
            }
            else
            {
             $session = new Session();
             $session->start();
             $session->set('id',$id);
            $res= $repository->edit($id);
        return $this->render('RepairLoginBundle:login:user.html.php',array('res'=>$res));

            }    
        }

    }

}

当admin使用role = 1登录时,它将呈现给success.html.php

在这个视图中我如何获得我在控制器中设置的会话变量。 我用过$ session-> get('id'); 它给我服务器错误,请帮助这个

1 个答案:

答案 0 :(得分:10)

最好使用Symfony2中的安全组件进行身份验证。 在The Book - Security中详细了解相关信息。您可能还应该查看FOSUserBundle

从symfony2中的PHP模板访问会话:

echo $app->getSession()->get('whatever');

会话处理

官方文档中有一篇文章: Components/HttpFoundation - Session Data Management

可以在此处找到会话组件的API文档: http://api.symfony.com/master/Symfony/Component/HttpFoundation/Session/Session.html

在symfony2标准版中,您可以从控制器中获取会话:

$session = $this->getRequest()->getSession();

由于您已在successAction中将请求作为参数,因此您可以使用以下命令访问会话:

$session = $request->getSession();

设置一个值($ value需要序列化):

$session->set('key',$value);

获取值:

$session->get('key');

保存(和关闭)会话可以通过以下方式完成:

$session->save();

您还应该参加SessionBag课程。 您创建一个SessionBag并将其注册到会话。见:

Symfony API

在注册的SessionBag中 - 实现AttributeBagInterface - 您可以根据需要获取和设置您的键/值。

提示:如果您想获得当前用户,并且您有一个容器感知控制器(注入容器)

你可以使用:

$user = $this->container->get('security.context')->getToken()->getUser();

如果你在标准版中扩展Symfony的Controller类 - 更短的方法是:

$user = $this->get('security.context')->getToken()->getUser();

甚至更短(Symfony> 2.1.x):

$user = $this->getUser();

替代方案(如果你的控制器不能识别容器):

将控制器定义为服务并注入@ security.context:

<强> YAML:

# src/Vendor/YourBundle/Resources/config/services.yml 

services:
    my.controller.service:
        class: Vendor\YourBundle\Controller\successController
        arguments: ["@security.context"]

<强>供应商\ YourBundle \控制器\ successController:

protected $securityContext;

public function __construct(SecurityContextInterface $securityContext)
{
    $this->securityContext = $securityContext;
}

然后在你的行动中:

$user = $this->securityContext->getToken()->getUser();

注意::如果您选择控制器即服务变体,则必须在路由中使用该服务。例如routing.yml:

[...]
route_name:
    pattern:  /success
    defaults: { _controller: my.controller.service:successAction }
    [...]
[...]

注意 ...您也可以使用“@ session”注入会话

 # src/Vendor/YourBundle/Resources/config/services.yml 
        [...]
        arguments: ["@security.context","@session"]

注意注入整个容器是资源匮乏的。高级开发人员逐个注入所需的服务,而不是整个容器。

提示:通常,控制器类使用大写首字母编写 - 例如:* S * uccessController

常规提示:您的示例中有不必要的代号:

       // 'if' and 'else' execute the same stuff here
       // result: dublicate code = more code = harder to read

       if($role == 1)
        {
            $session = new Session();
            $session->start();
            [...]
        }
        else
        {
            $session = new Session();
            $session->start();
            [...]
        }    

应该更好......

        // better: put this stuff before the if/else statement 

        $session = new Session();
        $session->start();

        if($role == 1)
        {
            [...]
        }
        else
        {
            [...]
        }