Service Symfony2在控制器中获取公共服务
大量墨水在Sf2控制器/容器周围流动。我面临以下情况:Service Symfony2在控制器中获取公共服务,service,dependency-injection,Service,Dependency Injection,大量墨水在Sf2控制器/容器周围流动。我面临以下情况: app/console container:debug security ... > 4 [container] Information for service security.token_storage Service Id security.token_interface Class Symfony\Component\Security\Core\Authentication\Token ... ... P
app/console container:debug security
...
> 4
[container] Information for service security.token_storage
Service Id security.token_interface
Class Symfony\Component\Security\Core\Authentication\Token ...
...
Public yes
LoginBundle\DefaultController.php
很明显,效果不错
LoginBundle\UserUtilsController
抛出:错误:对非对象调用成员函数get()
我发现:
在本例中,控制器扩展了Symfony的基本控制器,,它允许您访问服务容器本身。然后,您可以使用get方法从服务容器中查找和检索my_mailer服务
误解是:
-两个控制器都扩展了基本控制器,基本控制器本身扩展了ContainerWare,后者实现了设置容器的ContainerWareInterface。
-两个控制器访问相同的公共服务容器
那么,为什么第二个控制器不能工作呢
我知道这个问题由来已久,但我不想将控制器作为服务注入,我认为在services.yml中重新声明公共服务是多余和错误的
提前谢谢。我自己找到了答案,我想与大家分享,因为每个人的处境都一样。。。 UserUtilsController无法工作,因为它没有以这种方式工作。Symfony架构很有趣,如果你了解它的话 LoginBundle\Controller\UserUtilsController 服务.yml 所以我只是在我的新类中注入一个现有的服务 现在,要使用它,我们必须调用第一类: LoginBundle\Controller\DefaultController.php
在理解了Sf2 DI模型之后,上述解决方案几乎非常简单。我自己找到了答案,我想与大家分享,因为每个人都处于相同的情况下。。。 UserUtilsController无法工作,因为它没有以这种方式工作。Symfony架构很有趣,如果你了解它的话 LoginBundle\Controller\UserUtilsController 服务.yml 所以我只是在我的新类中注入一个现有的服务 现在,要使用它,我们必须调用第一类: LoginBundle\Controller\DefaultController.php 在理解了Sf2 DI模型之后,上述解决方案几乎非常简单
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction()
{
dump(Controller::get('security.token_storage'));
...
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class UserUtilsController extends Controller
{
public function getRoleById()
{
dump(Controller::get('security.token_storage'));
...
// For this job we don't need to extends any class..
class UserUtilsController
{
// but we need a property for injecting the service in it
private $token;
// Now let's inject service into our property $token
public function __construct($token)
{
$this->token = $token;
}
// It's not done but let pretend it is and let's use it
public function getRoleById()
{
...
return $this->token->getToken()->getRoles();
...
#here it's the magic
services:
# this is a new services container
user.loggeduser_utils:
# this is my class (second class)
class: LoginBundle\Controller\UserUtilsController
# this is how I feed my _construct argument
arguments: ["@security.token_storage"]
class DefaultController extends Controller
{
public function indexAction()
{
// because my class is now a service container we call in this way
$userRoleId = $this->get('user.loggeduser_utils');
...