简体   繁体   English

ZF2-在静态函数中使用Doctrine 2获取数据

[英]ZF2 - fetch data using Doctrine 2 in static function

I'm trying to figure out how to fetch data from database in my static function. 我试图弄清楚如何在我的静态函数中从数据库中获取数据。 Class looks like this: 类看起来像这样:

namespace Core

class Culture
{
    private static $allowedLanguages = array();

    public static function getAllowedLanguages()
    {
        if(empty(self::$allowedLanguages)){
            self::$allowedLanguages = $x // This should be data fetched from database
        }

        return $langs;
    }
}

In my code I want to be able to call \\Core\\Culture::getAllowedLanguages(); 在我的代码中,我希望能够调用\\Core\\Culture::getAllowedLanguages(); Problem that I have is how to access Doctrine 2 Repository from within my static class? 我的问题是如何从我的静态类中访问Doctrine 2存储库?

Is there an elegant way to get Doctrine entityManager or serviceLocator inside my function? 有没有一种优雅的方法可以在我的函数中获取DoctrineEntityManager或serviceLocator?

First you need this: 首先,您需要:

// use
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
/**
 * Get EntityManager
 */
public static function getEntityManager($module = 'PathInSrcForEntity')
{
    $paths = [dirname(__DIR__)."/src/$module/Entity"];
    $isDevMode = true;

    // the TEST DB connection configuration
    $connectionParams = [
            'driver'   => 'pdo_mysql',
            'user'     => 'root',
            'password' => 'root',
            'dbname'   => 'db_name',
    ];

    $config = Setup::createConfiguration($isDevMode);
    $driver = new AnnotationDriver(new AnnotationReader(), $paths);

    AnnotationRegistry::registerLoader('class_exists');
    $config->setMetadataDriverImpl($driver);

    $entityManager = EntityManager::create($connectionParams, $config);

    return $entityManager;
}

After that you call for Repository 之后,您需要调用存储库

// use
use Doctrine\ORM\Mapping\ClassMetadata;
$repository = new RepositoryNameRepository(\Core \Common::getEntityManager(), new ClassMetadata('\Path\Entity\ClassName'));

I found solution here: https://samsonasik.wordpress.com/2015/03/24/using-doctrine-data-fixture-for-testing-querybuilder-inside-repository/ 我在这里找到解决方案: https : //samsonasik.wordpress.com/2015/03/24/using-doctrine-data-fixture-for-testing-querybuilder-inside-repository/

You really should not use static methods, because you do then turbo pascal style functional programming (bug prone, hard to debug), not object oriented one. 您实际上不应该使用静态方法,因为您随后会进行涡轮Pascal风格的功能编程(容易出错,难以调试),而不是面向对象的编程。

In ZF2 you can easily register a service, inject it with Doctrine in the Factory, then use this service across the application: 在ZF2中,您可以轻松注册服务,在工厂中将其注入Doctrine,然后在整个应用程序中使用此服务:

$yourService = $this->getServiceLocator()->get(Culture::class);
print_r($yourService->getAllowedLanguages());

$yourService = $this->getServiceLocator()->get(Culture::class);
print_r($yourService->getAllowedLanguages());

// altough called twice
// data would be fetched only once since services
// are shared by default

If you still want to use static method, you have to inject doctrine into the class, for example in the onBootstrap method. 如果仍然要使用静态方法,则必须在该类中注入教义,例如在onBootstrap方法中。

Culture::setDoctrine($entityManager);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM