如何在 Symfony 中使用会话 [英] How to use session in Symfony

查看:30
本文介绍了如何在 Symfony 中使用会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解 symfony 会话的工作原理.
并且在 S.O. 上找不到我正在寻找的答案.或其他外部来源.

I'm getting a hard time trying to understand how symfony session works.
And couldn't find the answer I'm looking for here on S.O. or other external sources.

[设置]

  • Symfony 3
  • SiteEntity(保存网站信息,如网站网址、网站名称等)
  • 网站结构由页面周围的布局构成 (layout.html.twig)
  • Symfony 3
  • SiteEntity (Hold website informations such as site URL, site name, etc)
  • Website structure is made from a layout around the page (layout.html.twig)

[问题]

很容易理解,我就是不知道从哪里开始我的会话.我现在所做的是在 SiteController

Quite easy to understand, I just can't figure out where to start my session. What I did for now was create this action in SiteController

public function sessionAction(Request $request) {
    $em=$this->getDoctrine()->getManager();
    $site=$em->getRepository('SiteBundle:Site')->findOneBy(array('url'=>$request->getSchemeAndHttpHost()));
    if($site) {
        $session=new Session();
        $session->set('id',$site->getId());
        $session->set('url',$site->getUrl());
        $session->set('name',$site->getName());
    } else {
        [...]
    }
}

如何在网站加载时调用此函数来创建会话?

How can I call this function on website loading to create the session?

另外,这样做是否正确?

Also, is it the right way to do it?

推荐答案

好吧,首先非常感谢 Gopal Joshi 谁帮我弄清楚了很多事情... :)

Well, first a big thanks to Gopal Joshi who helped me figure out a lot of things... :)

对于那些后来来的人,阅读他的回答,它在很多方面都有帮助...
我还建议阅读此 问题,它与当前问题成对出现.

For those who come later, read his answer, it's helpful in a lot of ways...
I would also suggest reading this question, it goes in pair with the current question.

与此同时,我想出了这个:

Meanwhile, I came out with this:

1:注册服务

AppBundle\Resources\config\services.yml

app.session_handler:
    class: SalonBundle\Services\SessionHandler
    arguments:
        - "@doctrine"
        - "@router"
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: setSession }

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

First, I will point that I use the argument @router, but unless you need to redirect the response to another url, it's not needed.

2:创建服务

AppBundle\EventListener\SessionHandler.php

<?php

namespace AppBundle\EventListener;

use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class SessionHandler {

    private $doctrine;
    private $router;

    public function __construct(Registry $doctrine, Router $router) {
        //Make sure to type $doctrine and $router in the constructor.
        //Else some methods can't be found directly, and Symfony have to do the job for you
        //I guess it would make a big project a bit slower without the types
        $this->doctrine=$doctrine;
        $this->router=$router;
    }

    public function setSession(GetResponseEvent $responseEvent) {
        //This function parameter call on GetResponseEvent class
        //for the same reason as above.
        $site=$this->doctrine->getRepository('AppBundle:Site')->findOneBy(array('url'=>$responseEvent->getRequest()->getSchemeAndHttpHost()));
        if($site) {
            $session=$responseEvent->getRequest()->getSession();
            $session->clear();
            $session->set('site', $site);
        } else {
            if($responseEvent->getRequest()->get('_route') != 'some_route') {
                //This next line is the only reason as to why we pass "@router" as argument
                $responseEvent->setResponse(new RedirectResponse($this->router->generate('some_route')));
            }
        }
    }
}

总而言之,它非常接近 Gopal Joshi 答案...
其实是一样的,只是做了一些代码清理...
他和我的回答都在起作用...
唯一的区别是我的不会显示如下警告:
Method 'methodName()' not found or import 'import\path\and\name' is never used

To sum things up, it's very close to Gopal Joshi answer...
In fact, it's the same, just with some code cleanup...
Both his answer and mine are working...
The only difference is that mine won't show warning like:
Method 'methodName()' not found or import 'import\path\and\name' is never used

Gopal Joshi,如果你碰巧看到我的回答,我问你,我应该选择哪一个验证?
老实说,大部分学分是你的,所以我会验证你想要的答案......;)

Gopal Joshi, if you happen to read my answer, I'm asking you, which one should I validate?
Being honest here, most of the credits is yours, so I will validate the answer you want... ;)

这篇关于如何在 Symfony 中使用会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆