Get Symfony Container in an EntityRepository

You should not use $container in the EntityRepository. Instead, create a Model Manager service and inject the container through DI.


Bro, Symfony sometimes or lot of times is a headache, here is a hacky way, is not the correct like the @Tuong Le answer but is a horror do a lot for just a variable like was says @keyboardSmasher.

At the start of the function/method:

global $kernel;
if($kernel instanceOf \AppCache) $kernel = $kernel->getKernel();

So you can acces a container with

$kernel->getContainer();

hope this gives you time to go to walk in the park =),


If you are trying to access DBAL from EntityRepository class, you can use $this->getEntityManager()->getConnection() to get it.

Ex:

class CustomRepository extends EntityRepository
{
    public function myCustomFunction()
    {
        $conn = $this->getEntityManager()->getConnection();
        $stmt = $conn->query($sql);
        if ($stmt)
        {
            while ($row = $stmt->fetch())
                var_dump($row);
        }             
    }
}

Tags:

Php

Symfony