繁体   English   中英

Symfony 3使用__construct在服务中注入服务

[英]Symfony 3 Injecting Services in Services with __construct

在以下服务中注入服务时遇到问题: 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 /中调用412行上的var / cache / dev / appDevDebugProjectContainer.php

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

我迷失了这一点。 似乎我按照指南的指示操作,但是没有用...。

我在某处缺少东西...

如果您需要注入会话

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

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

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

这将是依赖注入。

您缺少创建方法:

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

暂无
暂无

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

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