2016-07-08 3 views
2

symfony2에서 "security.context"를 인수로 사용하여 새 서비스를 만들었습니다. 그러나 사용자 지정 클래스 나 컨트롤러가 아닌 클래스에서 서비스를 호출하면 항상 누락 된 인수 오류가 반환됩니다. 이 코드가 무엇이 잘못되었는지 알 수 있습니까?맞춤 클래스에서 서비스를 호출하면 symfony에서 Catchable Fatal Error가 반환됩니다.

내 서비스입니다.

appbundle.common.services.loggeduserservice: 
    class: Makubex\Pim\AppBundle\Common\Services\LoggedUserService 
    arguments: ["@security.context"] 

여기 내 서비스 클래스입니다.

use Symfony\Component\Security\Core\SecurityContext; 
class LoggedUserService{ 
private $context; 

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

public function getCurrentUser() 
{ 
    return $this->context; 
} 
} 

내 맞춤 클래스.

class makubex{ 

public function getUser(){ 
    $user = new LoggedUserService(); 
    echo $user->getId(); 
    } 
} 
+0

정확한 오류 메시지는 다음과 같습니다. Catchable Fatal Error : Makubex \ Pim \ AppBundle \ Common \ Services \ LoggedUserService :: __ construct()에 전달 된 인수 1이 Cubic \ Wamp \ www \ pim에서 호출 된 Makubex \ InfrastructureBundle \ Application \ AppContext의 인스턴스 여야합니다. 28 번째 줄에 있고 C : \ Wamp \ www \ pim \ src \ Makubex \ Pim \ AppBundle \ Common \ Services \ LoggedUserService.php 줄에 정의 된 \ src \ Makubex \ Pim \ AppBundle \ Backoffice \ CommandCustomAttributeCommandProcessor.php 줄 19 내부 서버 오류) – Makubex

답변

1

몇 가지 잘못된 여기에 있습니다 :

  1. 당신은 심포니 2.6 또는 security.context을 사용하지 않아야 새로운, 그것은 deprecated

  2. AppContext 인을 사용하는 경우 유효한 유형 힌트가되지 않는다 네가 주사하고있는 것 때문에. 당신은 아마 security.token_storage 서비스를 주입 할 당신은 다음 new 키워드 (예를 들어, new LoggedUserService())를 호출하여 클래스를 인스턴스화하지 않는 심포니의 서비스 컨테이너를 사용하려면 다음 유형의 힌트 TokenStorageInterface

  3. 이 될 것입니다. 대신 ContainerInterface 인스턴스 (예 : $user = $this->container->get('appbundle.common.services.loggeduserservice'))에서 get 방법으로 전화해야합니다. 그렇게하려면 커스텀 클래스 (makubex)의 컨테이너에 액세스 할 수 있어야합니다.

그래서, 결국 코드 같은 것을 보일 것입니다 :

services.yml을

appbundle.common.services.loggeduserservice: 
    class: Makubex\Pim\AppBundle\Common\Services\LoggedUserService 
    arguments: ["@security.token_storage"] 

서비스 클래스 :

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface 

class LoggedUserService{ 

    private $context; 

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

    public function getCurrentUser() 
    { 
     return $this->context; 
    } 
} 

클래스 :

,536,
class makubex{ 

    public function __construct($container) { 
     $this->container = $container; 
     //you need to inject container or just inject only instance of your LoggedUserService not whole container since this is considered as a bad practice 
    } 

    public function getUser(){ 
     $user = $this->container->get('appbundle.common.services.loggeduserservice'); 
     echo $user->getId(); 
    } 
} 
+0

안녕하세요 @ 토마스, 정말 고마워, 지금 일하고있어. – Makubex

관련 문제