简体   繁体   English

如何在Silex(Symfony)中处理会议

[英]How to work with sessions in Silex (Symfony)

My objective is to learn how to work with sessions in Silex 1.2 / Symfony. 我的目标是学习如何在Silex 1.2 / Symfony中进行会话。

  • First step is to create a session with Session() . 第一步是使用Session()创建会话。 I want to store it into $app['session'] . 我想将其存储到$app['session']
  • Second step is to access the data stored into session variable. 第二步是访问存储到会话变量中的数据。
  • Last step is to destroy session with invalidate() function. 最后一步是使用invalidate()函数销毁会话。

However, when I do: var_dump($app['session']->get('user')); 但是,当我这样做时: var_dump($app['session']->get('user')); I get this error: 我收到此错误:

Identifier "session" is not defined 标识符“会话”未定义

How can I access at $app['session'] from anywhere in my project ? 如何在项目中的任何位置通过$app['session']访问?

Routing and Controllers 路由和控制器

// create session
$routes->get('/test1', function () use ($app) {
    $app['session'] = new Symfony\Component\HttpFoundation\Session\Session();
    $app['session']->start();
    $app['session']->set('user', 'test');

    return $app['twig']->render('test1.html.twig');
})
->bind('test1');

// try to access on session data
$routes->get('/test2', function () use ($app){
    var_dump($app['session']->get('user'));

    return $app['twig']->render('test2.html.twig');
})
->bind('test2');

// remove session
$routes->get('/test3', function () use ($app){
    $app['session']->invalidate();

    return $app['twig']->render('test3.html.twig');
})
->bind('test3');

You're only defining the session service in your first route. 您仅在第一个路线中定义会话服务。 Any others don't have any idea about that identifier, so can't operate on it at all. 其他任何人对该标识符都不了解,因此根本无法对其进行操作。 Session data itself is persistent across requests, but not the actual creation of the service. 会话数据本身在请求中是持久的,但在服务的实际创建中不是持久的。

The lines 线

$app['session'] = new Symfony\Component\HttpFoundation\Session\Session();
$app['session']->start();

need to be moved outside of any route-specific configuration (usually into a configuration file such as src/app.php , although your structure might be different). 需要移到任何特定于路由的配置之外(通常移入配置文件,例如src/app.php ,尽管您的结构可能有所不同)。

$app['session'] will then be available to use in any of your routes/controller methods/etc. $app['session']将可用于您的任何路由/控制器方法/等中。

You might also want to look into using the SessionServiceProvider class instead, which will take care of registering this service and provide other useful benefits like saving the session at the end of the request/response cycle. 您可能还想研究使用SessionServiceProvider类,该类将负责注册此服务并提供其他有用的好处,例如在请求/响应周期结束时保存会话。 See https://silex.symfony.com/doc/1.3/providers/session.html 参见https://silex.symfony.com/doc/1.3/providers/session.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM