简体   繁体   English

[Symfony2]当前服务的用户

[英][Symfony2]current user in service

Hell, 地狱,

i try to use clankbundle for websocket use but i can't get my current user in my service 我尝试使用clankbundle进行websocket使用,但是我无法让当前用户使用我的服务

Call to a member function getUser() on a non-object in ...\\NotificationTopic.php 在... \\ NotificationTopic.php中的非对象上调用成员函数getUser()

my code : 我的代码:

-Service.YML -Service.YML

services:
    service_Default:
        class: Nuwland\WebBundle\Controller\CentreinteretController
        arguments: [ @doctrine.orm.entity_manager ]
    nuwland.web.notification:
        class: Nuwland\WebBundle\Topic\NotificationTopic
        arguments: ["@security.context"]
    kernel.listener.clank.client_event:
        class: Nuwland\WebBundle\EventListener\NuwlandClientEventListener
        arguments: ["@security.context"]
        tags:
            - { name: kernel.event_listener, event: clank.client.connected, method: onClientConnect }
            - { name: kernel.event_listener, event: clank.client.disconnected, method: onClientDisconnect }
            - { name: kernel.event_listener, event: clank.client.error, method: onClientError }

-NotificationTopic.php -NotificationTopic.php

<?php

namespace Nuwland\WebBundle\Services;

use JDare\ClankBundle\Topic\TopicInterface;
use Ratchet\ConnectionInterface as Conn;
use Symfony\Component\Security\Core\SecurityContext;


class NotificationTopic implements TopicInterface
{

   private $context;

    public function __construct(SecurityContext $securityContext){
        $this->context= $securityContext;
    }

    private function getUser(){
            return $this->context->getToken()->getUser();
    }
    /**
     * This will receive any Subscription requests for this topic.
     *
     * @param \Ratchet\ConnectionInterface $conn
     * @param $topic
     * @return void
     */
    public function onSubscribe(Conn $conn, $topic)
    {

     $userId = $this->getUser();
     var_dump($userId);
}

if anyone can help me, Thanks 如果有人可以帮助我,谢谢

Always check getToken() for null. 始终检查getToken()是否为null。 The user isn't authenticated in the system 用户未在系统中认证

You cant get user by calling: 您无法通过以下方式获得用户:

$this->context->getToken()->getUser()

Websocket server doesn't know anything about your application users. Websocket服务器对您的应用程序用户一无所知。 In this case - you must insert a 'clientManipulator' service into your topic and after it you can 在这种情况下,您必须在主题中插入“ clientManipulator”服务,之后您可以

$user = $this->clientManipulator->getClient($connection);

Do not forget to check that result is 'instanceof' your User object. 不要忘记检查结果是否是您的User对象的“实例”。 And remeber that websocket server has access to your session cookies (it must be in the same domain, or has access to another domain name) 并且请记住,websocket服务器可以访问您的会话cookie(它必须在同一域中,或者可以访问另一个域名)

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

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