我怎样才能在自定义存储库中注入类 - Symfony 2.7

时间:2017-05-16 18:23:59

标签: php symfony doctrine-orm silex

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

    class NewRepository extends EntityRepository
    {

        protected $fileUploader;



        public function __construct(EntityManager $em, Mapping\ClassMetadata $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;
        }

    }

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

1 个答案:

答案 0 :(得分:1)

由于版本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 \Doctrine\ORM\Mapping\ClassMetadata */
        $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

你很高兴去!