php - 如何在我的服务中使用学说方法(Symfony 4)?
问题描述
我在 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];
}
}
但我收到错误消息:
试图调用类“App\Service\PagesGenerator”的名为“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/服务.yaml”)。
解决方案
所以,在评论中我说最好让 Symfony 完成他的工作和自动装配EntityManager
。这是你应该做的。另外,你能告诉我们你使用的是什么 Symfony 版本以及是否启用了自动装配(检查 services.yaml 是否有)?
<?php
namespace App\Service;
use Doctrine\ORM\EntityManagerInterface;
class PagesGenerator
{
public function __construct(EntityManagerInterface $em) {
$this->em = $em;
}
public function getPages()
{
$page = $this->em->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];
}
}
推荐阅读
- rest - ReST (HTTP) 是否与向许多客户端应用程序广播数据相关
- laravel - 如何有效地重构 laravel 应用程序代码
- python - 将缺少的日期时间列添加到分组数据框中
- c# - 无法使用 Mono.Cecil 0.10.2 获取指令的行号
- ios - 不能在额外的类中外包 UICollectionViewDatasource
- spring-boot - 多个 @EnableBinding 与 Kafka Spring Cloud Stream
- c# - 将视图从一个控制器传递到另一个控制器的视图
- ruby-on-rails - 如果轨道中的 X 或 Y 条件
- c# - 每次更改字段时如何使用 NotifyPSEvent 触发事件?
- javascript - 如何在 javascript new Date() 中设置时区