Rxb*_*z18 -2 php symfony symfony4
我试图在我创建的服务的构造函数中注入像entityManager这样的公共服务,但我一直有这个错误:
函数App\Services\BillingInterface :: __ construct()的参数太少,在第144行的/var/www/.../src/Controller/TestController.php中传递了0,正好是预期的1.
在我的控制器中,服务是以不同的方法正确注入的,但在我创建的服务中,它不是在构造函数中注入的.
我没有更改services.yaml中的任何内容,因为文档说autowire在Symfony 4.2中是自动的
PS:我最近从Symfony 4.1更新到4.2,我不确定,但我认为它之前有效.
也许图书馆没有正确更新,但我没有发现任何错误.
服务代码:
#/src/Services/BillingInterface
namespace App\Services;
use Doctrine\ORM\EntityManagerInterface;
class BillingInterface {
private $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
}
Run Code Online (Sandbox Code Playgroud)
控制器代码:
namespace App\Controller;
use App\Services\BillingInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class TestController extends AbstractController {
public function teest(EntityManagerInterface $entityManager)
{
$billing = new BillingInterface();
}
}
Run Code Online (Sandbox Code Playgroud)
如果我使用$entityManagerController的参数实例化BillingInterface ,它可以工作,但我希望它直接在BillingInterface类构造函数中注入.
最后,这是Symfony文档中的内容:
// src/Service/MessageGenerator.php
// ...
use Psr\Log\LoggerInterface;
class MessageGenerator
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function getHappyMessage()
{
$this->logger->info('About to find a happy message!');
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
链接:https://symfony.com/doc/current/service_container.html
章:将服务/配置注入服务
所以,我不知道我的服务有什么问题.
谢谢您的回答.
由于您BillingInterface是一项服务 - 您需要使用Symfony容器提供的实例,而不是尝试自己实例化它.您的控制器需要注入此服务才能使用它:
namespace App\Controller;
use App\Services\BillingInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class TestController extends AbstractController
{
/**
* @var BillingInterface
*/
private $billing;
/**
* @param BillingInterface $billing
*/
public function __construct(BillingInterface $billing)
{
$this->billing = $billing;
}
public function teest(EntityManagerInterface $entityManager)
{
// Use $this->billing ...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
155 次 |
| 最近记录: |