Zend Framework 2 中服务中的实体管理器

2023-12-31

我为我的模块编写了自定义服务。该服务提供公共静态函数来验证给定的令牌。

现在我想实现另一个公共静态函数来检查 Doctrine-Entity 是否存在。对于这种情况,我需要服务中的对象管理器或服务定位器。

class ApiService 
{
    const KEY_LENGTH = 10;
    const USE_NUMBERS = true;
    const USE_CHARS = true;

    public static function isValid($apiKey) {
        $isValid = false;
        # more code tbd
        $isValid = self::exists($apiKey);
        return $isValid;
    }

    public static function exists($apiKey) {
    # Insert Object-Manager here

        $validator = new \DoctrineModule\Validator\ObjectExists(array(
           'object_repository' => $objectManager->getRepository('Application\Entity\User'),
           'fields' => array('email')
        )); 
    }
}
  1. 将我的函数实现为公共静态并将它们调用为静态方法是“最佳实践”吗?

  2. 将对象管理器注入我的最佳实践是什么doesEntityExist()功能?


最好的方法是从您的类中完全删除静态方法。 ZF2 使得通过名称获取服务变得非常容易,因此对于这样的用例,您不应该真正需要静态方法。

首先,清理你的服务:

namespace MyApp\Service;

use Doctrine\Common\Persistence\ObjectRepository;
use DoctrineModule\Validator\ObjectExists;

class ApiService
{
    // ...

    protected $validator;

    public function __construct(ObjectRepository $objectRepository)
    {
        $this->validator = new \DoctrineModule\Validator\ObjectExists(array(
           'object_repository' => $objectRepository,
           'fields'            => array('email')
        )); 
    }

    public function exists($apiKey)
    {
        return $this->validator->isValid($apiKey);
    }

    // ...
}

现在为其定义一个工厂:

namespace MyApp\ServiceFactory;

use MyApp\Service\ApiService;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ApiServiceFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $entityManager = $serviceLocator->get('Doctrine\ORM\EntityManager');
        $repository = $entityManager->getRepository('Application\Entity\User');

        return new ApiService($repository);
    }
}

然后将服务名称映射到工厂(通常在您的模块中):

namespace MyApp;

use Zend\ModuleManager\Feature\ConfigProviderInterface;

class Module implements ConfigProviderInterface
{
    public function getConfig()
    {
        return array(
            'service_manager' => array(
                'factories' => array(
                    'MyApp\Service\ApiService'
                        => 'MyApp\ServiceFactory\ApiServiceFactory',
                ),
            ),
        );
    }
}

NOTE:您可能只想简单地使用闭包而不是定义单独的工厂类,但是当您不使用该服务时,拥有工厂类可以给您带来小小的性能提升。另外,在配置中使用闭包意味着您无法缓存合并的配置,因此请考虑使用此处建议的方法。

这是一个没有工厂类的示例(再次考虑使用上面解释的方法):

namespace MyApp;

use Zend\ModuleManager\Feature\ServiceProviderInterface;

class Module implements ServiceProviderInterface
{
    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'MyApp\Service\ApiService' => function ($sl) {
                    $entityManager = $serviceLocator->get('Doctrine\ORM\EntityManager');
                    $repository = $entityManager->getRepository('Application\Entity\User');

                    return new MyApp\Service\ApiService($repository);
                },
            ),
        );
    }
}

现在您可以在控制器中使用该服务:

class MyController extends AbstractActionController
{
    // ...

    public function apiAction()
    {
        $apiService = $this->getServiceLocator()->get('MyApp\Service\ApiService');

        if ( ! $apiService->isValid($this->params('api-key')) {
            throw new InvalidApiKeyException($this->params('api-key'));
        }

        // ...
    }

    // ...
}

您还可以在有服务管理器的任何地方检索它:

$validator = $serviceLocator->get('MyApp\Service\ApiService');

作为附加建议,请考虑简化您的服务。自从isValid已经是验证器的一个方法,您可以简单地返回验证器本身(为简单起见,使用闭包方法):

namespace MyApp;

use Zend\ModuleManager\Feature\ServiceProviderInterface;
use DoctrineModule\Validator\ObjectExists;

class Module implements ServiceProviderInterface
{
    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'MyApp\Validator\ApiKeyValidator' => function ($sl) {

                    $entityManager = $serviceLocator->get('Doctrine\ORM\EntityManager');
                    $repository = $entityManager->getRepository('Application\Entity\User');
                    new ObjectExists(array(
                       'object_repository' => $objectRepository,
                       'fields'            => array('email')
                    )); 
                },
            ),
        );
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Zend Framework 2 中服务中的实体管理器 的相关文章

随机推荐

  • 捏合缩放和平移

    我有一个以 LinearLayout 作为主要布局的活动 在该布局中 有一个按钮可将视图 R layout motor block 添加到主布局 R id layout LayoutInflater inflater LayoutInfla
  • 重写句子,同时保留语义

    是否可以使用WordNet http wordnet princeton edu 重写一个句子 使句子的语义仍然相同 或大部分相同 假设我有这样一句话 Obama met with Putin last week 是否可以使用 WordNe
  • malloc()/free() 的对齐限制

    较旧的 K R 第二版 和我读过的其他 C 语言文本讨论了动态内存分配器的实现 其风格为malloc and free 通常还会顺便提及一些有关数据类型对齐限制的内容 显然 某些计算机硬件架构 CPU 寄存器和内存访问 限制了存储和寻址某些
  • 如何通过 Chrome 内容脚本下载文件?

    This 所以答案 https stackoverflow com a 24162238 1830334详细介绍了如何通过 Chrome 扩展程序下载文件 但我使用的是内容脚本 对 Chrome API 的访问受到限制 https deve
  • 使用 C# 删除项目时自动计算列表视图中项目的总价值

    我使用列表视图作为购物车 我需要知道当我删除商品时如何重新计算购物车的总价值 这是我添加到列表视图的代码 private void btnACart Click object sender EventArgs e int value 0 f
  • 从日期时间转换为 INT

    在我的 SSIS 包中 我必须将值从 DateTime 转换为相应的 INTEGER 值 已提供以下示例 关于如何转换这些有什么想法吗 DATETIME INT 1 1 2009 39814 2 1 2009 39845 3 1 2009
  • Visual Studio Community 2015 中的空白应用程序 (XAML) 等效项

    我正在阅读 Head First C 第 3 版 文本 其中包含特定于 VS 2012 的说明 但在 VS Community 2015 中找不到等效内容 文本显示使用 Windows Store gt Blank App XAML 开始一
  • 如何使用 Cython 将 python 函数作为参数传递给 c++ 函数

    这是我的设置 我有下一个要包装的 C 类 Foo h class Foo public typedef int MyType typedef int ArgType1 typedef int ArgType2 typedef MyType
  • Symfony2 Doctrine2 与两个拥有方和 Doctrine 命令行工具的多对多关系

    在我的 Symdony2 项目中 我有两个相关实体 Service 和 ServiceGroup 这应该是多对多关系 因为每个组可以有多个服务 每个服务可以属于多个组 此外 我需要一个用户界面来管理服务和组 因此 在编辑服务时 用户应该能够
  • 无法上传应用程序 - “上传到 itunes 商店时发生错误”

    我正在尝试将我的应用程序上传到商店 这不是第一次 所以我对这个过程很熟悉 我已尝试通过管理器 首选方法 和应用程序加载器进行尝试 但两者都提供了模糊的错误消息 我最近更新到 Xcode 4 试图修复它 我的存档项目验证一切正常 但在点击提交
  • for 循环没有按预期工作

    程序将询问用户该物品的代码 然后程序会将物品的状态更改为不可用 代码工作正常 它改变了状态 但 else 内的代码仍在运行 并且找不到打印项目 这是代码 public void stopSellingItem boolean invalid
  • XML 模式;有效属性值列表中的多个

    我对使用 XML 模式相当陌生 所以如果这比我自己认为的更微不足道 请原谅我的无能 我正在尝试创建一个必需属性 该属性必须包含列表中的 1 个或多个以空格分隔的字符串值 列表为4种典型的HTTP请求方式 get post put and d
  • 输入迭代器跳过空格,任何方法可以防止这种跳过

    我正在从文件读入字符串 直到到达分隔字符 美元符号 但输入迭代器会跳过空格 因此创建的字符串没有空格 在这种情况下不是我想要的 有什么办法可以阻止跳过行为吗 如果是这样怎么办 这是我的测试代码 include
  • 如何在 Nuxt 路由器中手动生成带有 .htaccess 404 页面回退的页面

    我正在尝试使用 Nuxt js 创建一个 SSG 网站 当我访问 nuxt config js 的生成属性中未设置的路由时 我想在不更改URL的情况下显示404页面的内容 使用htaccess 以下是正在建设中的现场 http we are
  • JasperReports 中的交叉表排序

    我在交叉表中有一个列组 它是一个字符串 它使用字段SectionName 还有一个领域 SectionID 整数 我想要排序的依据 I put F SectionID in the Sort By Expression但我收到错误 1 未找
  • Python 中的逆字典

    我正在尝试使用现有字典的值列表作为单独的键来创建一个新的字典 例如 dict1 dict a 1 2 3 b 1 2 3 4 c 1 2 我想获得 dict2 dict 1 a b c 2 a b c 3 a b 4 b 到目前为止 我还无
  • 如何生成符号信息以与 Linux 版本的英特尔 VTune Amplifier 一起使用?

    我正在使用英特尔 VTune Amplifier XE 2011 来分析我的程序的性能 我希望能够在分析结果中查看源代码 文档说我需要提供符号信息 不幸的是 它没有说明在编译我的程序时如何生成该符号信息 在 VTune 的 Windows
  • 如何访问 Android 中帐户验证器中设置的首选项

    我需要获取 CheckBoxPreference 和 SwitchPreference 的值 在 account preferences xml 我有
  • 正则表达式查找引号之间的值

    我有一个正则表达式来查找引号之间的值 1 1 这工作得很好 但是 如果引号之间有双引号 那么它会失败并也会将它们分开 例如 value1 value2 value with is here value4 我需要像这样的输出 value1 v
  • Zend Framework 2 中服务中的实体管理器

    我为我的模块编写了自定义服务 该服务提供公共静态函数来验证给定的令牌 现在我想实现另一个公共静态函数来检查 Doctrine Entity 是否存在 对于这种情况 我需要服务中的对象管理器或服务定位器 class ApiService co