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

ZF2 - fetch data using Doctrine 2 in static function

我想知道如何在我的静态函数中从数据库中获取数据。 Class 看起来像这样:

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

在我的代码中,我希望能够调用 \Core\Culture::getAllowedLanguages(); 我遇到的问题是如何从我的静态 class?

中访问 Doctrine 2 Repository

有没有一种优雅的方法可以在我的函数中获取 Doctrine entityManager 或 serviceLocator?

你真的不应该使用静态方法,因为你会做 turbo pascal 风格的函数式编程(容易出错,难以调试),而不是面向对象的。

在 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

如果您仍想使用静态方法,则必须将原则注入 class,例如在 onBootstrap 方法中。

Culture::setDoctrine($entityManager);

首先你需要这个:

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

之后调用 Repository

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

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