0
votes

Im trying to insert data into database in onKernelRequest using doctrine

//** 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();
     }
}

but i get error below

Undefined method 'persist'. The method name must start with either findBy or findOneBy!

Here is the manager which i take the entity manager from, i take entity from here because i tried both $this->get('doctrine') or $this->getDoctrine() inside onKernelRequest but error

//** 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

1 Answers

1
votes

It looks like you're setting $em to a repository, not an entity manager. If you just do $em = $this->am->em it oughta work.