【发布时间】:2019-03-05 09:45:32
【问题描述】:
我在 Symfony 中创建了我自己的第一个服务:
// src/Service/PagesGenerator.php
namespace App\Service;
class PagesGenerator
{
public function getPages()
{
$page = $this->getDoctrine()->getRepository(Pages::class)->findOneBy(['slug'=>$slug]);
$messages = [
'You did it! You updated the system! Amazing!',
'That was one of the coolest updates I\'ve seen all day!',
'Great work! Keep going!',
];
$index = array_rand($messages);
return $messages[$index];
}
}
但我收到错误消息:
试图调用类的名为“getDoctrine”的未定义方法 “应用\服务\页面生成器”。
然后我尝试在我的 services.yaml 中添加:
PagesGenerator:
class: %PagesGenerator.class%
arguments:
- "@doctrine.orm.entity_manager"
然后我收到错误消息:
文件“/Users/work/project/config/services.yaml”不包含 /Users/work/project/config/services.yaml 中的有效 YAML(即 加载到资源“/Users/work/project/config/services.yaml”中)。
【问题讨论】:
-
Symfony 正在使用称为依赖注入的神奇模式。不要在
services.yaml中为您的服务提供任何参数,而是在您的服务中调用__construct(EntityManagerInterface $em)并让Symfony 注入您的实体管理器。在我看来,这要清楚得多。 -
@GasKa 非常感谢。这听起来真的很好。能给我举个例子吗。我试图将此行放入我的服务中,但我收到错误
syntax error, unexpected '$em' -
我认为您使用了
$em而不是$this->em。此外,您必须在__construct()之前为您的服务声明此属性。 -
正如我在上一个问题中所说的那样:阅读文档。使用自动装配是 Symfony 最佳实践的一部分。
-
但不阅读文档?再次:使用自动装配。
标签: php symfony doctrine-orm