Symmfony & Sonata:如何从 AbstractAdmin 扩展访问 EntityManagerInterface?
Posted
技术标签:
【中文标题】Symmfony & Sonata:如何从 AbstractAdmin 扩展访问 EntityManagerInterface?【英文标题】:Symmfony & Sonata : How to access EntityManagerInterface from AbstractAdmin extends? 【发布时间】:2020-02-18 22:18:26 【问题描述】:我有一个扩展 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
我错过了什么?
【问题讨论】:
错误消息是关于 ClientAdmin 但您显示了 TotoAdmin 的代码? 【参考方案1】:你正在扩展一个已经有 __construct 的类
当我在 Sonata's 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;
还有一点就是需要配置成服务according to the docs
services:
App\Admin\TotoAdmin:
arguments: [~, ~, ~, '@doctrine.orm.entity_manager']
我觉得应该可以
【讨论】:
以上是关于Symmfony & Sonata:如何从 AbstractAdmin 扩展访问 EntityManagerInterface?的主要内容,如果未能解决你的问题,请参考以下文章
Symfony Sonata Admin:如何从 DB 中获取选择数组