Marcos García
Marcos García

Reputation: 622

Get Symfony Container in an EntityRepository

I've set a variable in parameters.ini, but now I want to retrieve that variable from an EntityRepository and $this->container is unset so I can't do it

How should I get to the container?

Thanks :)

Upvotes: 8

Views: 15085

Answers (5)

Felipe Buccioni
Felipe Buccioni

Reputation: 19668

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 =),

Upvotes: 10

nnscr
nnscr

Reputation: 39

If you really only need to pass an argument to the service, you can just pass it without needing a manager, like:

services:
    your_service:
        class: YourServiceClass
        arguments: [%some.parameter%]

Upvotes: 1

aTTozk
aTTozk

Reputation: 127

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);
        }             
    }
}

Upvotes: 5

Juan Sosa
Juan Sosa

Reputation: 5280

You can retrieve your variable from the Controller as usual, and pass it to the EntityRepository if you define a custom repository method. For example:

public function findAllOrderedByFoo($your_variable)
{
    //use $your_variable here

    return $this->getEntityManager()
        ->createQuery(  your SQL here   )
        ->getResult();
}

Upvotes: 1

Tuong Le
Tuong Le

Reputation: 19220

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

Upvotes: 9

Related Questions