Zend Framework 2中的实体经理 [英] Entity Manager in Service in Zend Framework 2

查看:81
本文介绍了Zend Framework 2中的实体经理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为我的模块编写了一个定制服务。此服务提供公共静态函数,该函数应该验证给定的令牌。



现在我想实现另一个公共静态函数来检查是否存在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'=>数组('email')
));
}
}




  1. 是实现我的函数为public static并将其称为静态方法最佳实践?


  2. 将对象管理器注入我的 doesEntityExist()函数?



解决方案

最好的方法是在这里完全删除你的类的静态方法。 ZF2使得它们的名字可以很容易地获取服务,所以你不应该真的需要这种用例的静态方法。



首先,清理你的服务:

 命名空间MyApp\Service; 

使用Doctrine\Common\Persistence\ObjectRepository;
使用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);
}

// ...
}

现在为它定义一个工厂:

 命名空间MyApp\ServiceFactory; 

使用MyApp\Service\ApiService;
使用Zend\ServiceManager\FactoryInterface;
使用Zend\ServiceManager\ServiceLocatorInterface;

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

返回新的ApiService($ repository);
}
}

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

 命名空间MyApp; 

使用Zend\ModuleManager\Feature\ConfigProviderInterface;

class模块实现ConfigProviderInterface
{
public function getConfig()
{
return array(
'service_manager'=> array
'工厂'=>数组(
'MyApp\Service\ApiService'
=>'MyApp\ServiceFactory\ApiServiceFactory',
),
),
);
}
}

注意:你可以想要简单地使用闭包,而不是定义一个单独的工厂类,但是当你没有使用这个服务时,工厂类给你一个小的性能提升。此外,在配置中使用闭包意味着您无法缓存合并的配置,因此请考虑使用此处提出的方法。



下面是没有工厂类的示例(再次考虑使用上述方法):

 命名空间MyApp; 

使用Zend\ModuleManager\Feature\ServiceProviderInterface;

class模块实现ServiceProviderInterface
{
public function getServiceConfig()
{
返回数组(
'工厂'=>数组
'MyApp\Service\ApiService'=> function($ sl){
$ entityManager = $ serviceLocator-> get('Doctrine\ORM\EntityManager');
$ repository = $ entityManager-> getRepository('Application\Entity\User');

返回新的MyApp\Service\ApiService($ repository);
}
),
);
}
}

现在您可以使用控制器中的服务: / p>

  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 已经是您的验证器,您可以简单地返回验证器本身(特此使用闭包方法简单):

 命名空间MyApp; 

使用Zend\ModuleManager\Feature\ServiceProviderInterface;
使用DoctrineModule\Validator\ObjectExists;

class Module imp lements ServiceProviderInterface
{
public function getServiceConfig()
{
return array(
'factoryories'=> 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'=>数组('email')
));
},
),
);
}
}


I have written a custom service for my module. This service provides public static functions which should validate a given token.

Now i want to implement another public static function which checks if an Doctrine-Entity exists or not. For this case i need the object-manager or the service-locator in my service.

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. Is it "best-practice" to implement my functions as public static and call them as static methods?

  2. What is the best practice to inject the object-manager into my doesEntityExist() function?

解决方案

The best approach would be to completely remove the static methods from your class here. ZF2 makes it really easy to fetch services by their name, so you shouldn't really need static methods for such a use case.

First of all, clean up your service:

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);
    }

    // ...
}

Now define a factory for it:

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);
    }
}

Then map the service name to the factory (usually in your module):

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: you may want to simply use a closure instead of defining a separate factory class, but having factory classes gives you a small performance boost when you're not using the service. Also, using a closure in configuration means you cannot cache the merged configuration, so consider using the method suggested here.

Here's an example without the factory class (again, consider using the approach explained above):

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);
                },
            ),
        );
    }
}

Now you can use the service in your controllers:

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'));
        }

        // ...
    }

    // ...
}

You can also retrieve it wherever you have the service manager:

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

As an additional suggestion, consider simplifying your service. Since isValid is already a method of your validator, you could simply return the validator itself (hereby using the closure method for simplicity):

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')
                    )); 
                },
            ),
        );
    }
}

这篇关于Zend Framework 2中的实体经理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆