首页 > 解决方案 > Symmfony & Sonata:如何从 AbstractAdmin 扩展访问 EntityManagerInterface?

问题描述

我有一个扩展 AbstractAdmin 的类。我尝试将 EntityManagerInterface 注入:

namespace App\Admin;

use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CountryType;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityManagerInterface;

    final class TotoAdmin extends AbstractAdmin
    {    
        /**
         * @var EntityManagerInterface
         */
        private $em;

        /**
         * @param EntityManagerInterface $em
         */
        public function __construct(EntityManagerInterface $em)
        {
            $this->em = $em;
        }

它导致一个空白页。当我做

php bin/console cache:clear

我得到错误:

  Argument 1 passed to App\Admin\ClientAdmin::__construct() must implement interface Doctrine\ORM\EntityManagerInterface, string given, c  
  alled in /var/www/projects/csiquote/var/cache/dev/ContainerF5etCaE/getAdmin_CategoryService.php on line 26 

我错过了什么 ?

标签: symfonysonataconstruct

解决方案


您正在扩展一个已经具有 __construct 的类

当我在Sonata 的 github AbstractAdmin.php上查找时, 原来的类构造函数是

 /**
 * @param string $code
 * @param string $class
 * @param string $baseControllerName
 */
public function __construct($code, $class, $baseControllerName)
{
    $this->code = $code;
    $this->class = $class;
    $this->baseControllerName = $baseControllerName;
    $this->predefinePerPageOptions();
    $this->datagridValues['_per_page'] = $this->maxPerPage;
}

因此,如果您需要像 EntityManagerInterface 这样的额外依赖项,您可以复制原件并将新的添加到末尾。然后也调用父构造函数

 private $em;

/**
 * @param string $code
 * @param string $class
 * @param string $baseControllerName
 * @param EntityManagerInterface $em
 */
public function __construct($code, $class, $baseControllerName, EntityManagerInterface $em)
{
    parent::__construct($code, $class, $baseControllerName);

    $this->em = $em;
}

另一件事是您需要根据文档将其配置为服务

services:
    App\Admin\TotoAdmin:
        arguments: [~, ~, ~, '@doctrine.orm.entity_manager']

我认为这应该有效


推荐阅读