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

bha*_*ari 3 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));

            }    
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

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

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

Nic*_*ich 10

应该使用Symfony2中的安全组件更好地完成前期身份验证.在The Book - Security中了解更多相关信息.您可能还应该看看FOSUserBundle

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

echo $app->getSession()->get('whatever');
Run Code Online (Sandbox Code Playgroud)

会话处理

官方文档中有一篇文章: Components/HttpFoundation - 会话数据管理

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

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

$session = $this->getRequest()->getSession();
Run Code Online (Sandbox Code Playgroud)

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

$session = $request->getSession();
Run Code Online (Sandbox Code Playgroud)

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

$session->set('key',$value);
Run Code Online (Sandbox Code Playgroud)

获得一个价值:

$session->get('key');
Run Code Online (Sandbox Code Playgroud)

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

$session->save();
Run Code Online (Sandbox Code Playgroud)

你也应该沉迷于SessionBag类.您创建一个SessionBag并将其注册到会话.看到:

Symfony API

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

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

您可以使用:

$user = $this->container->get('security.context')->getToken()->getUser();
Run Code Online (Sandbox Code Playgroud)

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

$user = $this->get('security.context')->getToken()->getUser();
Run Code Online (Sandbox Code Playgroud)

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

$user = $this->getUser();
Run Code Online (Sandbox Code Playgroud)

备选方案(如果您的控制器不支持容器):

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

YAML:

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

services:
    my.controller.service:
        class: Vendor\YourBundle\Controller\successController
        arguments: ["@security.context"]
Run Code Online (Sandbox Code Playgroud)

卖方\ YourBundle \控制器\ successController:

protected $securityContext;

public function __construct(SecurityContextInterface $securityContext)
{
    $this->securityContext = $securityContext;
}
Run Code Online (Sandbox Code Playgroud)

然后在你的行动中:

$user = $this->securityContext->getToken()->getUser();
Run Code Online (Sandbox Code Playgroud)

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

[...]
route_name:
    pattern:  /success
    defaults: { _controller: my.controller.service:successAction }
    [...]
[...]
Run Code Online (Sandbox Code Playgroud)

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

 # src/Vendor/YourBundle/Resources/config/services.yml 
        [...]
        arguments: ["@security.context","@session"]
Run Code Online (Sandbox Code Playgroud)

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

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

一般提示:您的示例中有不必要的dublicate代码:

       // '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();
            [...]
        }    
Run Code Online (Sandbox Code Playgroud)

应该更好......

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

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

        if($role == 1)
        {
            [...]
        }
        else
        {
            [...]
        }   
Run Code Online (Sandbox Code Playgroud)