【问题标题】:Symfony 3 Injecting Services in Services with __constructSymfony 3 使用 __construct 在服务中注入服务
【发布时间】:2018-01-22 13:43:13
【问题描述】:

在以下服务中注入服务时遇到问题: https://symfony.com/doc/current/service_container.html#injecting-services-config-into-a-service

这段代码:

namespace ServicesBundle\Services;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManagerInterface;

class Services
{

private $email;

public function __construct($email, $message, SessionInterface $sessInt) {

    $this->email = $email;
    $this->message = $message;
    $this->sessInt = $sessInt;

}

public function DisplayMessage(){


    return "This is the Services Class in the Services namespace. Email the administrator @ " . $this->email . " | " . $this->message;

}

public function sessionIdGetAction(){
    $hello = $this->sessInt->getID();
    return $hello;
}
}

抛出此错误:

类型错误:传递给 ServicesBundle\Services\Services::__construct() 的参数 3 必须实现接口 Symfony\Component\HttpFoundation\Session\SessionInterface,没有给出,在 /home/admin-daniel/symfony-test-sites 中调用/july262017/var/cache/dev/appDevDebugProjectContainer.php 第 412 行

当我从我的控制器调用这些函数中的任何一个时。

我迷路了。似乎我按照指南所说的但没有工作....

我在某处遗漏了一些东西......

【问题讨论】:

    标签: php symfony


    【解决方案1】:

    如果需要注入Session

    service:
       my.service.name:
          class: ..\MyClassName
          arguments: 
            session: "@session"
    

    【讨论】:

    • 我在发布问题后就在思考这个问题。阅读您的答案并立即查看。非常感谢。
    • 欢迎@dlhines,您可以将问题设置为已回答吗?谢谢。
    • @dlhines 您能否将问题标记为已回答?只需点击✔️标志。
    【解决方案2】:

    它在第 412 行的 /home/admin-daniel/symfony-test-sites/july262017/var/cache/dev/appDevDebugProjectContainer.php 中说 您需要传递具有 SessionInterface 类型的对象作为第三个参数。 而你没有这样做。

    您需要将私有属性$sessInt 添加到您的服务类。因为在构造函数中有$this->sessInt = $sessInt;

    这将是依赖注入。

    【讨论】:

    • 好的。我知道了。您的答案以及第一个答案有助于我理解它。非常感谢。
    • 我很高兴能帮上忙。顺便说一句 - 你也需要有私人 $message。
    【解决方案3】:

    您缺少创建方法:

    public static function create(ContainerInterface $container) {
            return new static(
              $container->get('yourvariable')
            );
        }
    

    【讨论】:

      猜你喜欢
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 2017-01-13
      • 2015-10-24
      • 2019-11-02
      • 2017-03-01
      • 1970-01-01
      • 2012-08-01
      相关资源
      最近更新 更多