Symfony2访问自定义类中的Doctrine Entity Manager

时间:2012-04-03 15:33:54

标签: symfony doctrine-orm

更新:

如果您需要在自定义类中使用Entity Manager,您可以这样:

将此代码放入您的捆绑包中:

use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpFoundation\Request;
require_once DIR . '/../../../app/bootstrap.php.cache';
require_once DIR . '/../../../app/AppKernel.php';

class ApplicationBoot {
  private static $kernel;

  public static function getContainer() {
    if(self::$kernel instanceof \AppKernel) {
      if(!self::$kernel->getContainer() instanceof Container){
        self::$kernel->boot();
    }            
    return self::$kernel->getContainer();
  }

  $environment = 'prod';
  if (!array_key_exists('REMOTE_ADDR', $_SERVER) || in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1', 'localhost'))) {
    $environment = 'dev';
  }

  self::$kernel = new \AppKernel($environment, false);
  self::$kernel->boot();
  return self::$kernel->getContainer();
  }

  public static function shutDown() {
    self::$kernel->shutdown();
}}

现在您可以访问EntityManager:

$container = ApplicationBoot::getContainer();
$entityManager = $container->get('doctrine')->getEntityManager();

2 个答案:

答案 0 :(得分:2)

我还没有看到像这样的服务文件:

arguments:
  entityManager: "@doctrine.orm.entity_manager"

可能应该是:

arguments: [@doctrine.orm.entity_manager]

更新:

基于一些评论,您似乎正在尝试:

$job = new PostJob();

期待实体经理以某种方式通过。这不是事情的运作方式。你需要这样做:

$job = $this->get('postjob.service.id');

为了让Symfony 2依赖注入工作。查看服务手册中的章节。一开始看起来有点过分,但是一旦你获得了一些服务,那么它就变成了第二天性。

答案 1 :(得分:1)

要从您的捆绑中加载services.yml,您需要提供extension class

// src/Vendor/YourBundle/DedendencyInjection/VendorYourBundleExtension.php

namespace Vendor\YourBundle\DependencyInjection;

use Symfony\Component\HttpKernel\DependencyInjection\Extension,
    Symfony\Component\DependencyInjection\ContainerBuilder,
    Symfony\Component\DependencyInjection\Loader\YamlFileLoader,
    Symfony\Component\Config\FileLocator;

class VendorYourBundleExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }
}