使用 Symfony4 创建带有参数的动态函数

Create dynamic function with arguments using Symfony4

我是 symfony 4 的新手,我已经完成了 CRUD。我想通过创建一个可以减少它的函数来增强我的代码。

示例:

如果你有 2 个模块,比如管理事件和公告(当然你会在这里添加、获取所有、删除和更新)。而不是像这样的长代码。

 $fetch_item = $this->getDoctrine()
                    ->getRepository(Event::class)
                    ->findAll();

我想像 $fetch = $this->fetch(Event::class) 这样缩短它我在我的服务目录中创建了一个新文件。

Service\Crud.php

<?php 

namespace App\Service;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

/**
 * 
 */
class Crud extends AbstractController
{

    public function __construct(){
        parent::__construct(); 
    }

    public function fetch($table)
    {
        $fetch_item = $this->getDoctrine()
                        ->getRepository($table)
                        ->findAll();

        return $fetch_item;
    }
}


?>

控制器

//
...
use App\Service\Crud;

    ...
    class EventController extends AbstractController
     public function index()
        {
            // $fetch_item = $this->getDoctrine()
         //                 ->getRepository(Item::class)
         //                 ->findAll();
            $fetch = $this->fetch(Item::class);
            return $this->render('base.html.twig',array(
                'items'         => $fetch_item

            ));
        }

上面是我的代码,但它给我一个错误 "Attempted to call an undefined method named "fetch" of class "App\Controller\ItemController""

问题:如何创建一个函数来减少我的代码?

fetch 函数没有理由成为控制器的一部分(相反,有很多理由不是)。您需要的是简单的服务:

<?php

namespace App\Service;

use Doctrine\ORM\EntityManagerInterface;

class CrudService {

    protected $em;

    public function __construct(EntityManagerInterface $em){
        $this->em = $em;
    }

    public function fetch($entityClass) {

        return $this->em->getRepository($entityClass)->findAll();

    }
}

然后在你的控制器中,你只需通过自动装配注入它并使用它:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Service\CrudService;
use App\Entity\Item;
...

class EventController extends AbstractController {
    public function index(CrudService $crudService) {
        $items = $crudService->fetch(Item::class);

        return $this->render('base.html.twig',array(
            'items' => $items
        ));
    }

}