如何在自定义存储库中注入类 - Symfony 2.7



我有自定义存储库类,我必须在其中注入帮助我上传文件的类,并在需要时擦除文件。我扩展了实体存储库构造函数,但我不知道如何在自定义存储库类中添加第三个参数。

    class NewRepository extends EntityRepository
    {
        protected $fileUploader;

        public function __construct(EntityManager $em, MappingClassMetadata $class,FileUploader $fileUploader)
        {
            parent::__construct($em, $class);
        }
        public function create($data, Item $item = null)
        {
            $em = $this->getEntityManager();
            if(!$item) $item = new Item();
            if(isset($data['file'])) {
                $image = $this->fileUploader->setFile($data['file'])->uploadFile();
                $data['filename'] = $image['filename'];
                $data['image_url'] = $image['file_url'];
            }
            $item->setTitle($data['title']);
            $item->setDescription($data['description']);
            $em->persist($item);
            $em->flush($item);
            return $item;
        }
    }

我总是收到传递给构造函数的第三个参数为空的错误。

自 2.4 版起,Doctrine 使用RepositoryFactory来实例化存储库,并作为入门为您提供DefaultRepositoryFactory。为了能够将其他依赖项注入您的存储库,您需要推出上述工厂的实现(为了简洁起见,我省略了所有use语句(:

class YourRepositoryFactory implements RepositoryFactory
{
    private $fileUploader;
    public function __construct(FileUploader $fileUploader)
    {
        $this->fileUploader = $fileUploader;
    }
    public function getRepository(EntityManagerInterface $entityManager, $entityName)
    {
        $repositoryHash = $entityManager->getClassMetadata($entityName)->getName() . spl_object_hash($entityManager);
        if (isset($this->repositoryList[$repositoryHash])) {
            return $this->repositoryList[$repositoryHash];
        }
        return $this->repositoryList[$repositoryHash] = $this->createRepository($entityManager, $entityName);
    }
    private function createRepository(EntityManagerInterface $entityManager, $entityName)
    {
        /* @var $metadata DoctrineORMMappingClassMetadata */
        $metadata            = $entityManager->getClassMetadata($entityName);
        $repositoryClassName = $metadata->customRepositoryClassName
            ?: $entityManager->getConfiguration()->getDefaultRepositoryClassName();
        switch ($repositoryClassName) {
            case NewRepository::class:
                return new $repositoryClassName($entityManager, $metadata, $this->fileUploader);
            default:
                return new $repositoryClassName($entityManager, $metadata);
        }
    }
}

以您喜欢的方式将工厂注册为服务后,您需要通过以下方式调整doctrine配置:

doctrine:
    orm:
        repository_factory: name.of.your.factory.service

你很好去!

相关内容

  • 没有找到相关文章