Session Symfony:如何在include Twig控制器中设置cookie和会话变量?

Session Symfony:如何在include Twig控制器中设置cookie和会话变量?,session,cookies,controller,twig,symfony,Session,Cookies,Controller,Twig,Symfony,这是我的第一篇帖子,如果有任何问题,请告诉我:) 我正在使用Symfony建立一个网站,但我目前遇到了一个问题: 我无法在include-Twig控制器{render(controller(“AcmeCoreBundle:Auth:index”))}中设置cookie和会话变量(或者肯定遗漏了一些内容)(此控制器必须允许从每个网站页面进行“连接”) 我已经使用实体WhoIsIt和表单类型WhoIsIt创建了表单 <?php namespace Acme\CoreBundle\Contro

这是我的第一篇帖子,如果有任何问题,请告诉我:)

我正在使用Symfony建立一个网站,但我目前遇到了一个问题: 我无法在include-Twig控制器
{render(controller(“AcmeCoreBundle:Auth:index”))}
中设置cookie和会话变量(或者肯定遗漏了一些内容)(此控制器必须允许从每个网站页面进行“连接”)

我已经使用实体
WhoIsIt
和表单类型
WhoIsIt
创建了表单

<?php

namespace Acme\CoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Cookie;
use Acme\CoreBundle\Form\WhoIsItType;
use Acme\CoreBundle\Entity\WhoIsIt;

class AuthController extends Controller
{
    public function indexAction(Request $request)
    {

        $who = new WhoIsIt;
        $session = $this->get('session');
        $response = new Response();
        $form = $this->get('form.factory')->create(WhoIsItType::class, $who);

        if ($request->isMethod('POST')) {
          $form->handleRequest($request);
          if ($form->isValid()) {
              $whoisit = $form->getData();
              //I set Cookie and Session variables

              $response->headers->setCookie(new Cookie('personality', $whoisit->getPersonality(), time() + 3600 * 24 * 3));
              $session->set('personality', $whoisit->getPersonality());
              $response->setContent($this->render('AcmeCoreBundle:Form:Auth.html.twig', array(
                        'form' => $form->createView())));
              return $response;
          }
    }

    $cookies = $request->cookies;
    $who->setPersonality($this->setDefault('personality', 'personality.supporter', $cookies, $session));
    $form = $this->get('form.factory')->create(WhoIsItType::class, $who);
    $response->setContent($this->render('AcmeCoreBundle:Form:Auth.html.twig', array(
        'form' => $form->createView())));
    return $response;
}

private function setDefault($element, $default, $cookies, $session)
{
//This fonction help me to define the default value of the form
    if ($session->has($element))
    {
        return $session->get($element);
    }
    elseif ($cookies->has($element))
    {
        return $cookies->get($element);
    }
    return $default;
}
}
不要获取名为
personality

我想知道是否可以在子请求中设置cookie/会话? 如果这是可能的,我应该在代码中更改什么

我希望你能理解我的问题:)如果你不理解,或者需要更精确的解释,请让我知道并发表评论


感谢您的帮助。

这是我访问我的网站时创建会话的方式:
我需要检查站点url以找到正确的实体。希望它能帮助你

1:注册服务

AppBundle\Resources\config\services.yml

首先,我将指出我使用了参数
@router
,但是除非您需要将响应重定向到另一个url,否则不需要它

2:创建服务

AppBundle\EventListener\SessionHandler.php


这是我访问网站时创建会话的方式:
我需要检查站点url以找到正确的实体。希望它能帮助你

1:注册服务

AppBundle\Resources\config\services.yml

首先,我将指出我使用了参数
@router
,但是除非您需要将响应重定向到另一个url,否则不需要它

2:创建服务

AppBundle\EventListener\SessionHandler.php


嗯,我找到了解决问题的办法

对于我的第一个问题,我需要给出原始请求作为参数:

{{ render(controller("AcmeCoreBundle:Auth:index", {'cookies': app.request.cookies})) }}
并做一些其他黑客(js重定向等)

但是,现在我使用另一个控制器捕捉“POST”,因此,当我创建表单时,我需要指定一个选项:

$form = $this->get('form.factory')->create(WhoIsItType::class, $who, array(
                        'action' => $this->generateUrl('acme_core_auth'))
                        );
然后我创建正确的操作:

public function authAction (Request $request)
    {
        $who = new WhoIsIt;
        $session = $this->get('session');
        $form = $this->get('form.factory')->create(WhoIsItType::class, $who);
        if ($request->isMethod('POST')) {
            $form->handleRequest($request);
            if ($form->isValid()) {
                $whoisit = $form->getData();                    
                $response = new RedirectResponse($request->headers->get('referer')); //Here I create a redirection to the current webpage
                $response->headers->setCookie(new Cookie('personality', $whoisit->getPersonality(), time() + 3600 * 48)); I set a new cookie in the response header
                $session->set('personality', $whoisit->getPersonality()); // I update session var
                return $response;         

            }
        }
        return $this->redirectToRoute('acme_core_homepage'); //If not in post/valid I redirect to the homepage
    }
最后,代码是:

Acme\CoreBundle\Controller\AuthController.php


嗯,我找到了解决问题的办法

对于我的第一个问题,我需要给出原始请求作为参数:

{{ render(controller("AcmeCoreBundle:Auth:index", {'cookies': app.request.cookies})) }}
并做一些其他黑客(js重定向等)

但是,现在我使用另一个控制器捕捉“POST”,因此,当我创建表单时,我需要指定一个选项:

$form = $this->get('form.factory')->create(WhoIsItType::class, $who, array(
                        'action' => $this->generateUrl('acme_core_auth'))
                        );
然后我创建正确的操作:

public function authAction (Request $request)
    {
        $who = new WhoIsIt;
        $session = $this->get('session');
        $form = $this->get('form.factory')->create(WhoIsItType::class, $who);
        if ($request->isMethod('POST')) {
            $form->handleRequest($request);
            if ($form->isValid()) {
                $whoisit = $form->getData();                    
                $response = new RedirectResponse($request->headers->get('referer')); //Here I create a redirection to the current webpage
                $response->headers->setCookie(new Cookie('personality', $whoisit->getPersonality(), time() + 3600 * 48)); I set a new cookie in the response header
                $session->set('personality', $whoisit->getPersonality()); // I update session var
                return $response;         

            }
        }
        return $this->redirectToRoute('acme_core_homepage'); //If not in post/valid I redirect to the homepage
    }
最后,代码是:

Acme\CoreBundle\Controller\AuthController.php


您好,非常感谢您的关注和非常详细的回答。目前我对服务不太熟悉。然后我继续挖掘,找到了一个解决问题的方法,就是不使用服务。将张贴我的解决方案,希望这将有助于。您好,非常感谢您的兴趣和您非常详细的回答。目前我对服务不太熟悉。然后我继续挖掘,找到了一个解决问题的方法,就是不使用服务。将张贴我的解决方案,希望这将有所帮助。
<?php

namespace Acme\CoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Cookie;
use Acme\CoreBundle\Form\WhoIsItType;
use Acme\CoreBundle\Entity\WhoIsIt;

class AuthController extends Controller
{
    public function indexAction($cookies)
    {

        $who = new WhoIsIt;
        $session = $this->get('session');
        $who->setPersonality($this->setDefault('personality', 'eventType.All', $cookies, $session));
        $form = $this->get('form.factory')->create(WhoIsItType::class, $who, array(
                            'action' => $this->generateUrl('acme_core_auth'))
                            );
        return $this->render('AcmeCoreBundle:Form:Auth.html.twig', array(
            'form' => $form->createView()));
    }

    public function authAction (Request $request)
    {
        $who = new WhoIsIt;
        $session = $this->get('session');
        $form = $this->get('form.factory')->create(WhoIsItType::class, $who);
        if ($request->isMethod('POST')) {
            $form->handleRequest($request);
            if ($form->isValid()) {
                $whoisit = $form->getData();
                $response = new RedirectResponse($request->headers->get('referer'));
                $response->headers->setCookie(new Cookie('personality', $whoisit->getPersonality(), time() + 3600 * 48));
                $session->set('personality', $whoisit->getPersonality());
                return $response;         
            }
        }
        return $this->redirectToRoute('acme_core_homepage');
    }

    //This set default according to the order session>cookies>default
    private function setDefault($element, $default, $cookies, $session)
    {
        if ($session->has($element))
        {
            return $session->get($element);
        }
        if ($cookies->has($element))
        {
            $default = $cookies->get($element);
        }
        $session->set($element, $default);
        return $default;
    }
}