![](/img/trans.png)
[英]Doctrine2 in Symfony2: How can I see which object-call leads into a query?
[英]Symfony2: How can i see a list of open sessions
可以在Symfony2中获取打开的会话列表吗? 我需要它来检查当前是否特别打开了一个会话。
谢谢。
能否查看哪些会话已打开取决于您使用的SessionHandler
。
symfony-standard
代理使用的默认会话处理程序是php的本机会话,称为NativeFileSessionHandler
。 该处理程序将会话信息存储在文件中,这使得很难提取会话数据。
为了能够轻松访问会话信息,可以将symfony配置为使用它提供的数据库驱动的SessionSaveHandlers之一( 文档 )。
在文档一章如何使用PdoSessionHandler在数据库中存储会话中可以找到有关如何实现这些的示例。
然后,您可以创建Session
实体/存储库,并像其他任何实体一样使用教义来查询会话信息。 同样,您可以覆盖默认的会话处理程序并更改垃圾收集器,即标记用户未定期注销以显示提醒消息的会话。
可以通过设置CustomSaveHandler将会话数据写入数据库。 请参阅文档: http : //symfony.com/doc/current/components/http_foundation/session_configuration.html#custom-save-handlers
之后,您可以查询会话表。
在控制器中
UserController类扩展BaseController {
/**
* Constructor
*/
public function __construct() {
parent::__construct();
}
/**
* @return \Symfony\Component\HttpFoundation\Response
*/
public function whoIsOnlineAction() {
$session_dir = ini_get('session.save_path');
$sessions = preg_grep('/^([^.])/', scandir($session_dir));
$logged_in_user_array = array();
$one_hour_ago = strtotime( '-1 hour');
foreach( $sessions as $key => $session ) {
$session_file_contents = file_get_contents( $session_dir . '/' . $session );
$decoded_array = $this->unserialize_php( $session_file_contents, '|' );
$updated = $decoded_array['_sf2_meta']['u'];
if( !is_null($decoded_array['_sf2_attributes']['_security_secured_area'] ) ){
$decoded_array2 = self::unserialize_php( $decoded_array['_sf2_attributes']['_security_secured_area'], '"' );
$keys = array_keys($decoded_array2);
if( $one_hour_ago < $updated ) $logged_in_user_array[$decoded_array2 [$keys[4]][0].''] = str_replace( array( 'domain1\\', 'domain2\\'), '', $decoded_array2 [$keys[4]][0].'');
}
}
return $this->render( 'HubBundle:Core:active_users.html.twig', array(
'users' => $logged_in_user_array
) );
}
/**
* @param $session_data
* @param $delimiter
* @return array
* @throws \Exception
*/
private static function unserialize_php($session_data, $delimiter) {
$return_data = array();
$offset = 0;
while ($offset < strlen($session_data)) {
if (!strstr(substr($session_data, $offset), $delimiter)) {
throw new \Exception("invalid data, remaining: " . substr($session_data, $offset));
}
$pos = strpos($session_data, $delimiter, $offset);
$num = $pos - $offset;
$varname = substr($session_data, $offset, $num);
$offset += $num + 1;
$data = unserialize(substr($session_data, $offset));
$return_data[$varname] = $data;
$offset += strlen(serialize($data));
}
return $return_data;
}
}
在模板中:
{% if is_granted('IS_AUTHENTICATED_REMEMBERED') and is_granted('ROLE_ADMIN') %}
<div class="profile-menu shadowed">{{ render(controller('BaseBundle:User:whoIsOnline')) }}</div>
{% endif %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.