Symfony2如何在Listener中获取实体管理器

时间:2014-12-10 03:13:16

标签: php symfony doctrine

我试图使用doctrine

在onKernelRequest中将数据插入数据库
//** src/MPN/CRMBundle/Listener/AnalyticsListener.php
namespace MPN\CRMBundle\Listener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use MPN\CRMBundle\Manager\AnalyticsManager;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManager;
use vRonn\StatisticsBundle\Entity\Statistics as Statistics;

class AnalyticsListener
{
    /**
     * @var AnalyticsManager
     */
    private $am;

    private $em;

    public function __construct(AnalyticsManager $am)
    {
        $this->am = $am;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        if (!$event->isMasterRequest()) {
            return;
        }

        $request    = $event->getRequest();
        $session    = $request->getSession();
        $uri        = $request->getRequestUri();
        $route      = $request->get('_route');
        if (!preg_match('@^/(app_dev\.php/)?(admin|js|media|_[^/]+)/?.*@', $uri)) {
            // add page view count
            $this->am->addPageView();

            //Here is how i try to insert data
            $d = new Statistics();
            $d->setType(1);
            $d->setName('blabla');
            $d->setValue('val');

            $em = $this->am->em->getRepository('vRonnStatisticsBundle:Statistics');
            $em->persist($d);
            $em->flush();

            if (!$session->has('visitor') || $session->get('visitor') < time()) {
                $session->set('visitor', time() + (24 * 60 * 60));
                $this->am->addVisitor();
            }
            $this->am->save();
     }
}

但我得到错误

  

未定义的方法'持久'。方法名称必须以其中一个开头   findBy或findOneBy!

以下是我接受实体经理的经理,我从这里拿实体,因为我尝试了 $ this-&gt; get('doctrine') $ this-&gt ; onKernelRequest 中的getDoctrine()但错误

//** src/MPN/CRMBundle/Manager/AnalyticsManager.php
namespace MPN\CRMBundle\Manager;

use Doctrine\ORM\EntityManager;
use MPN\CRMBundle\Entity\Analytics;
use MPN\CRMBundle\Service\DateTimeBuilder;

class AnalyticsManager
{
    /**
     * @var EntityManager
     */
    public $em;

    /**
     * @var DateTimeBuilder
     */
    private $dateTimeBuilder;

    /**
     * @var array
     */
    private $analytics;

    public function __construct(EntityManager $em, DateTimeBuilder $dateTimeBuilder)
    {
        $this->em = $em;
        $this->dateTimeBuilder = $dateTimeBuilder;
        $this->setup();
    }

    /**
     * Flushes the data to the database.
     *
     * @return void
     */
    public function save()
    {
        $this->em->flush();
    }
}

1 个答案:

答案 0 :(得分:1)

您似乎将$em设置为存储库,而不是实体管理器。如果你只是做$em = $this->am->em它就可以了。