如何在Controller以外的类中获取环境

时间:2017-02-28 08:47:00

标签: php symfony

我想使用环境

通常我可以在Controller中获得这样的environemnt。

$this->container->get(‘kernel’)->getEnvironment(); 

然而除了Controller之外,我怎么能做到?

我的想法如下所示。

制作原创课程以获得环境。

namespace Acme\TopBundle\MyServices;
use Doctrine\ORM\EntityManager;

class MyFunc
{
    private $em;
    private $env;
    public function __construct(EntityManager $em,$env)
    {
        $this->em = $em;
        $this->env = $env;
    }

    public function getEnv(){
        return $this->env;
    }

然后在config.yml中注册服务

services:
    myfunc:
        class:   Acme\TopBundle\MyServices\MyFunc
        arguments: [@doctrine.orm.entity_manager,"%kernel.environment%"]

然后例如在admin类中我如何获得环境?

namespace Acme\AdminBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use FOS\UserBundle\Model\UserManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Ivory\GoogleMap\Places\AutocompleteType;
class PlaceCatAdmin extends Admin
{
   public function configureListFields(ListMapper $listMapper)
    {
   // I want to get environment here

2 个答案:

答案 0 :(得分:1)

该容器已通过管理池在管理类中可用。

您可以像这样检索它:

$this->getConfigurationPool()->getContainer()->getParameter('kernel.environment');

供参考:

https://github.com/sonata-project/SonataAdminBundle/blob/3.x/Admin/AbstractAdmin.php

/**
 * @return Pool
 */
public function getConfigurationPool()
{
    return $this->configurationPool;
}

https://github.com/sonata-project/SonataAdminBundle/blob/3.x/Admin/Pool.php

  /**
     * @var ContainerInterface
     */
    protected $container;

答案 1 :(得分:0)

要通过服务访问您的环境变量不是一个好主意,但是如果有任何这样的要求那么您可以通过这种方式实现这一点:

namespace Acme\TopBundle\MyServices;
use Doctrine\ORM\EntityManager;

class MyFunc
{
    private $em;
    private $env;
    public function __construct(EntityManager $em,$env)
    {
        $this->em = $em;
        $this->env = $env;
    }

    public function getEnv(){
        return $this->env;
    }

服务配置原样。 然后在你的管理员控制器访问这个:

namespace Acme\AdminBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use FOS\UserBundle\Model\UserManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Ivory\GoogleMap\Places\AutocompleteType;
class PlaceCatAdmin extends Admin
{
   public function configureListFields(ListMapper $listMapper)
    {
      $env = $this->container->get('myfunc')->getEnv();

如果您将ENV变量视为公共,那么您也可以通过这种方式访问​​

$env = $this->container->get('myfunc')->env;