如何在我的服务中使用学说方法(Symfony 4)?

pea*_*ove 0 php symfony doctrine-orm

我在 Symfony 中创建了我自己的第一个服务:

// src/Service/PagesGenerator.php 
Run Code Online (Sandbox Code Playgroud)

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];
    }
}
Run Code Online (Sandbox Code Playgroud)

但我收到错误消息:

试图调用类“App\Service\PagesGenerator”的名为“getDoctrine”的未定义方法。

然后我尝试添加到我的 services.yaml 中:

PagesGenerator:
    class: %PagesGenerator.class%
    arguments:
      - "@doctrine.orm.entity_manager"
Run Code Online (Sandbox Code Playgroud)

但后来我收到错误消息:

文件“/Users/work/project/config/services.yaml”在/Users/work/project/config/services.yaml(加载在资源“/Users/work/project/config/服务.yaml”)。

Gas*_*sKa 8

所以,在评论中我说让 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];
    }
}
Run Code Online (Sandbox Code Playgroud)