ZF2 - fetch data using Doctrine 2 in static function

时间:2015-06-26 10:23:07

标签: php doctrine-orm zend-framework2

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(); Problem that I have is how to access Doctrine 2 Repository from within my static class?

Is there an elegant way to get Doctrine entityManager or serviceLocator inside my function?

2 个答案:

答案 0 :(得分:2)

首先你需要这个:

Template.icons.onRendered(function () {
    template.$('.demo-default').tooltipster({
        offsetY: 2,
         theme: 'tooltipster-shadow'
    })
});

之后你要求存储库

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

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

答案 1 :(得分:1)

你真的不应该使用静态方法,因为你会进行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

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

Culture::setDoctrine($entityManager);