如何在Symfony2中获取root目录

use*_*999 5 php symfony

我想在symfony2中获取根目录.

如果我使用:

$this->get('kernel')->getRootDir();
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

FatalErrorException: Error: Call to undefined method Test\Component\ClassLoader\DebugClassLoader::get() 
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

Jim*_*mbo 20

编辑,看到这篇文章已经引起了如此多的关注而且我的位于顶部,获取根目录的最佳方法是将其作为构造函数参数传递给您的类.您可以使用services.yml以下参数:

serviceName:
  class: Name\Of\Your\Service
  arguments: %kernel.root_dir%
Run Code Online (Sandbox Code Playgroud)

然后,当框架实例化时,以下代码将为其提供根目录:

namespace Name\Of\Your;

class Service
{
    public function __construct($rootDir)
    {
        // $rootDir is the root directory passed in for you
    }
}
Run Code Online (Sandbox Code Playgroud)

下面的答案的其余部分是在不使用依赖注入的情况下做旧的,糟糕的方式.


我想让每个人都知道这是一个反模式服务定位器.任何开发人员都应该只能从方法签名中查看类或控制器所需的功能.注入一个完整的"容器"是非常通用的,难以调试,并不是最好的做事方式.您应该使用依赖注入容器,它允许您在应用程序的任何位置专门注入您想要的内容.请明确点.查看一个名为Auryn的非常棒的递归实例化依赖注入容器.在框架解析控制器/操作的位置,将其放在那里并使用容器创建控制器并改为运行该方法.繁荣!即时SOLID代码.

你是对的,使用访问服务容器$this->get('service').

但是,为了使用$this->get(),您将需要访问该get()方法.

控制器访问

通过确保控制器扩展Symfony使用的基本控制器类,您可以访问此方法和许多其他方便的方法.

确保您引用了正确的Controller基类:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class HelloController extends Controller
{
    /** The Kernel should now be accessible via the container **/
    $root = $this->get('kernel')->getRootDir();
}
Run Code Online (Sandbox Code Playgroud)

服务访问

如果要从服务访问容器,则必须将控制器定义为服务.您可以在这篇文章中找到更多信息,这篇文章这篇文章有关如何执行此操作.另一种有用的链接.无论哪种方式,你现在都知道要寻找什么.这篇文章也可能有用:

use Symfony\Component\DependencyInjection\ContainerInterface; 

class MyClass
{
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function doWhatever()
    {
        /** Your container is now in $this->container **/
        $root = $this->container->get('kernel')->getRootDir();
    }
}
Run Code Online (Sandbox Code Playgroud)

在config.yml中,定义新类型:

myclass:
  class: ...\MyClass
  arguments: ["@service_container"]
Run Code Online (Sandbox Code Playgroud)

您可以在文档中阅读有关服务容器的更多信息.


Bro*_*cha 11

该参数kernel.root_dir指向app目录.通常要到达根目录,我用户kernel.root_dir/../

所以在控制器中你可以使用 $this->container->getParameter('kernel.root_dir')."/../"

在服务定义中,您可以使用:

my_service:
    class: \Path\to\class
    arguments: [%kernel.root_dir%/../]
Run Code Online (Sandbox Code Playgroud)