Symfony2监听器类没有加载?

时间:2011-12-31 09:57:55

标签: symfony doctrine-orm

我正在努力寻找可能听起来很愚蠢的事情,但是:

我创建了一个侦听器类,在实体持久化后将内容添加到Lucene搜索索引。

我的config.yml:

services:
searchindexer.listener:
    class: ripr\WfBundle\Listener\SearchIndexer
    tags:
        - { name: doctrine.event_listener, event: postPersist }

我的文件位于src / ripr / WfBundle / Listener

文件名是SearchIndexer.php

班级名称是SearchIndexer

命名空间是ripr \ WfBundle \ Listener

我在这一行收到错误

$index = $this->get('ivory_lucene_search')->getIndex('identifier1');

错误:

Fatal error: Call to a member function get() on a non-object

这听起来我没有加载课程。我无法得到我错的地方。

我将dev缓存倍数刷新。

当我在经典的控制器中调用它时,这条精确的线条非常有效。

-------- --------已编辑

我的班级代码帮助

 <?php

namespace ripr\WfBundle\Listener;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\ORM\Event\LifecycleEventArgs;
use ripr\WfBundle\Entity\Item;
use Ivory\LuceneSearchBundle\Model\Document;
use Ivory\LuceneSearchBundle\Model\Field;

/**
 * Search indexer.
 *
 * 
 */

class SearchIndexer extends Controller
 {

    /**
     * Index content
     *
     */
    public function postPersist (LifeCycleEventArgs $args) {

        //  $luceneSearch = $this->get('ivory_lucene_search');
        //  $luceneSearch->eraseIndex('identifier1');

            $entity = $args->getEntity();
            $entityManager = $args->getEntityManager();

            // perhaps you only want to act on some "Product" entity


                $index = $this->get('ivory_lucene_search')->getIndex('identifier1');
                $document = new Document();
                $document->addField(Field::text('titre', 'bille'));
                $document->addField(Field::text('texte', 'billou'));
            // Add your document to the index
                $index->addDocument($document);
                $index->commit();






    }

}

1 个答案:

答案 0 :(得分:3)

这种情况正在发生,因为默认情况下您无权访问侦听器类中的容器。但是,不要只从Controller扩展您的类(它可以访问容器)或注入整个容器。相反,只注入您需要的服务:

config.yml:

services:
  searchindexer.listener:
    class: ripr\WfBundle\Listener\SearchIndexer
    arguments:
      luceneSearch: "@ivory_lucene_search"
    tags:
      - { name: doctrine.event_listener, event: postPersist }

SearchIndexer.php:

class SearchIndexer
{
    protected $luceneSearch;

    public function __constructor($luceneSearch)
    {
        $this->luceneSearch = $luceneSearch;
    }

    // ...

然后,您需要在侦听器中使用lucene搜索,只需调用$this->luceneSearch