BLa*_*uRE 5 doctrine symfony symfony4
我有一个控制器
use Doctrine\ORM\EntityManagerInterface:
class ExampleController{
public function someFunction(ExampleService $injectedService){
$injectedService->serviceFunction();
}
}
Run Code Online (Sandbox Code Playgroud)
有服务
use Doctrine\ORM\EntityManagerInterface;
class ExampleService{
public function __construct(EntityManagerInterface $em){
...
}
}
Run Code Online (Sandbox Code Playgroud)
但是,someFunction()由于传递了0个参数(未注入EntityManagerInterface),导致调用失败。我正在尝试从服务中使用EntityManager。自动接线功能已开启。我已经尝试过Symfony3的解决方案,但是除非我缺少某些东西,否则它们似乎无法工作。
编辑:这是我的services.yaml:
services:
_defaults:
autowire: true
autoconfigure: true
public: false
App\:
resource: '../src/*'
exclude: '../src/{Entity,Migrations,Tests,Kernel.php}'
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
Run Code Online (Sandbox Code Playgroud)
小智 7
仅在Symfony 4中使用。
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Name; //if you use entity for example Name
class ExampleService{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
function newName($code) // for example with a entity
{
$name = new Name();
$name->setCode($code); // use setter for entity
$this->em->persist($name);
$this->em->flush();
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这是一个旧帖子,但以防万一有人为此而苦恼,use 语句中有一个错字:
use Doctrine\ORM\EntityManagerInterface: //<- see that's a colon, not a semicolon
Run Code Online (Sandbox Code Playgroud)
具有自动装配功能的经典 symfony 服务使用构造函数注入方法来注入依赖项。就您而言,您没有构造函数。
您可以考虑添加构造函数方法并设置对私有类属性的依赖关系。并相应地使用。
或者您可以使用setter 注入。
服务配置:
services:
app.example_controller:
class: Your\Namespace\ExampleController
calls:
- [setExampleService, ['@exampleService']]
Run Code Online (Sandbox Code Playgroud)
控制器类:
class ExampleController
{
private $exampleService;
public function someFunction() {
$this->exampleService->serviceFunction();
}
public function setExampleService(ExampleService $exampleService) {
$this->exampleService = $exampleService;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11031 次 |
| 最近记录: |