symfony - 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
我错过了什么 ?
解决方案
您正在扩展一个已经具有 __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']
我认为这应该有效
推荐阅读
- excel - 应用程序或对象定义的错误 1004 错误
- c++ - 如何在 CPU 上计算矢量变换?
- python - 为内部为白色,外部为黑色的多边形创建图像
- javascript - 当我运行项目时,我使用本机警告:ViewPager Android 已从 react-native 中提取?
- database - 如何将 MIT App Inventor 中的联系人导入数据库(tinydb 或 firebase)?
- python - 为没有写入权限的用户在网络驱动器上安装 Python
- python - 将列表项附加到字典,Python
- python - 为什么 TensorBoard 显示错误的余弦距离?
- java - 在switch语句的情况下如何使用&&运算符?
- python - Python,Keras - 二进制文本分类器预测结果为值数组而不是单个概率