在 ZF2 中创建具有依赖关系(依赖注入)的学说存储库

2024-08-09php开发问题
1

本文介绍了在 ZF2 中创建具有依赖关系(依赖注入)的学说存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想创建一个具有硬依赖关系的存储库.我发现 Jurian Sluiman 的这篇博文 但他建议从服务管理器获取存储库并在需要时将其注入到服务中.

I want to make a repository with hard dependencies. I found this blog post by Jurian Sluisman but he suggests getting the repository from the service manager and injecting it into the service where needed.

如果我能够使用 getRepository 从我的 EntityManagerObjectManager 实例中获取具有注入依赖项的自定义存储库,那就更好了 方法:

It would be much better if I would be able to get my custom repositories with injected dependencies like normally from my EntityManager or ObjectManager instance by using the getRepository method:

$objectManager->getRepository('MyEntityClass');

如何在我的存储库中使用构造函数注入,并且仍然像往常一样直接使用 getRepository 方法从 ObjectManager 获取它们?

How can I use constructor injection in my Repositories and still get them like normally from the ObjectManager directly with the getRepository method?

推荐答案

Doctrine 使用 一个工厂类 DoctrineORMEntityManagerInterfaceDefaultRepositoryFactory 用于创建存储库实例.如果未设置自定义工厂,则会创建此默认工厂 在 getRepositoryFactory 方法 rel="nofollow noreferrer">DoctrineORMConfiguration 类.

Doctrine uses a factory class DoctrineORMEntityManagerInterfaceDefaultRepositoryFactory for creating repository instances. If no custom factory is set this default factory is created here in the getRepositoryFactory method in the DoctrineORMConfiguration class.

通过定义一个自定义的repository_factory,我们可以覆盖这个默认的工厂类,并将自定义逻辑添加到将注入硬依赖的工厂:

By defining a custom repository_factory we can overwrite this default factory class and add custom logic to the factory that will inject the hard dependencies:

为了说明如何做到这一点,我将展示一个示例,其中存储库工厂类通过构造函数注入创建依赖于 ServiceLocator 实例的存储库.

To illustrate how you can do this I will show an example where the repository factory class creates repositories that are dependent on a ServiceLocator instance through constructor injection.

1) 制作一个自定义工厂类,实现RepositoryFactory 接口

1) make a custom factory class that implements the doctrine RepositoryFactory interface

这个类看起来很像学说的DefaultRepositoryFactory类.

<?php

namespace MyORMRepository;

use DoctrineCommonPersistenceObjectRepository;    
use DoctrineORMRepositoryRepositoryFactory;
use DoctrineORMEntityManagerInterface;
use ZendServiceManagerServiceLocatorAwareInterface;
use ZendServiceManagerServiceLocatorAwareTrait;
use ZendServiceManagerServiceLocatorInterface;

class CustomRepositoryFactory implements RepositoryFactory, ServiceLocatorAwareInterface
{
    use ServiceLocatorAwareTrait;

    /**
     * @var ObjectRepository[]
     */
    private $repositoryList = array();

    /**
     * @var ServiceLocator
     */
    protected $serviceLocator;

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

    /**
     * {@inheritdoc}
     */
    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);
    }

    /**
     * @param EntityManagerInterface $entityManager The EntityManager instance.
     * @param string                 $entityName    The name of the entity.
     * @return ObjectRepository
     */
    private function createRepository(EntityManagerInterface $entityManager, $entityName)
    {
        /* @var $metadata DoctrineORMMappingClassMetadata */
        $metadata            = $entityManager->getClassMetadata($entityName);
        $repositoryClassName = $metadata->customRepositoryClassName
            ?: $entityManager->getConfiguration()->getDefaultRepositoryClassName();

        // Constructor injection, I check with subclass of but it is just an example
        if(is_subclass_of($repositoryClassName, ServiceLocatorAwareInterface::class)){
            $serviceLocator = $this->getServiceLocator()
            $repository = new $repositoryClassName($entityManager, $metadata, $serviceLocator);
        }else{
            $repository = new $repositoryClassName($entityManager, $metadata);
        }
        return $repository;
    }
}

2) 为存储库工厂创建工厂

<?php
namespace MyORMRepositoryFactory;

use MyORMRepositoryCustomRepositoryFactory;
use ZendCacheStorageStorageInterface;
use ZendServiceManagerFactoryInterface;
use ZendServiceManagerServiceLocatorInterface;

class CustomRepositoryFactoryFactory implements FactoryInterface
{
    /**
     * @param  ServiceLocatorInterface $serviceLocator
     * @return StorageInterface
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return new CustomRepositoryFactory($serviceLocator);
    }
}

3) 在service_manager 配置中为仓库工厂注册工厂

3) register the factory for the repository factory in the service_manager config

'service_manager' => array(
    'factories' => array(
        'MyORMRepositoryCustomRepositoryFactory' => 'MyORMRepositoryFactoryCustomRepositoryFactoryFactory'
    )
)

4) 在教义配置中注册存储库工厂

'doctrine' => array(
    'configuration' => array(
        'orm_default' => array(
            'repository_factory' => 'MyORMRepositoryCustomRepositoryFactory'
        )
    )
)

这篇关于在 ZF2 中创建具有依赖关系(依赖注入)的学说存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

PHP实现DeepL翻译API调用
DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以...
2025-08-20 php开发问题
168

PHP通过phpspreadsheet导入Excel日期数据处理方法
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的...
2024-10-23 php开发问题
287

mediatemple - 无法使用 codeigniter 发送电子邮件
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)...
2024-08-23 php开发问题
11

Laravel Gmail 配置错误
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)...
2024-08-23 php开发问题
16

将 PHPMailer 用于 SMTP 的问题
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)...
2024-08-23 php开发问题
4

关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)...
2024-08-23 php开发问题
17