首页 > 解决方案 > 如何在我的服务中使用学说方法(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”)。

标签: phpsymfonydoctrine-orm

解决方案


所以,在评论中我说最好让 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];
    }
}

推荐阅读