Get Symfony Container in an EntityRepository

后端 未结 5 1205
无人共我
无人共我 2020-12-15 11:56

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

相关标签:
5条回答
  • 2020-12-15 12:22

    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();
    }
    
    0 讨论(0)
  • 2020-12-15 12:33

    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%]
    
    0 讨论(0)
  • 2020-12-15 12:38

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

    0 讨论(0)
  • 2020-12-15 12:43

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

    0 讨论(0)
  • 2020-12-15 12:46

    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);
            }             
        }
    }
    
    0 讨论(0)
提交回复
热议问题