2016-04-23 132 views
1

当我试着使用,以获得当前目录:Symfony2的:获取当前目录错误

$this->container->getParameter('kernel.root_dir').'/../web/

我得到这个错误:Fatal error: Using $this when not in object context in C:\XXX on line 124

代码:

class AdminController { 

/** 
* Add event controller. 
* 
* @param Request $request Incoming request 
* @param Application $app Silex application 
*/ 
public function addEventAction(Request $request, Application $app) { 
    $event = new Event(); 
    $types= $app['dao.type']->findAllSelectList(); 
    $eventForm = $app['form.factory']->create(new EventType($types), $event); 
    $eventForm->handleRequest($request); 
    if ($eventForm->isSubmitted() && $eventForm->isValid()) { 
     var_dump($event->getCoverImageLink()); 
     $file = $event->getCoverImageLink(); 
     $fileName = md5(uniqid()).'.'.$file->guessExtension(); 
     var_dump($fileName); 
     //$path = $this->container->getParameter('kernel.root_dir').'/../web';//$this->get('kernel')->getRootDir() . '/../web'; 
     var_dump($this); 
     $app['dao.event']->save($event); 
     $app['session']->getFlashBag()->add('success', 'The event was successfully created.'); 
    } 
    return $app['twig']->render('event_form.html.twig', array(
     'title' => 'New event', 
     'eventForm' => $eventForm->createView())); 
} 

如何请修复此错误?什么是正确的功能使用?

+0

你在哪里把这个代码?该错误消息表明您没有将代码放在类中(或者您正在使用的方法是'static')。 – xabbuh

+0

不仅如此,而且你的代码中没有$ this->容器。 – Cerad

+0

我真的不知道如何得到这个目录。什么是使用功能? – YoannLth

回答

0

看起来您使用的是Silex而不是Symfony 2。作为一个非常简约的框架,silex并没有为您提供Symfony所做的所有配置和依赖注入的好东西。

能够检索应用程序根目录的最简单方法是自己在bootstrap.php中定义它。只需在上面添加的东西是这样的:

define('APP_ROOT', __DIR__ . '/../'); 

现在你可以使用常量在你的控制器:

public function addEventAction(Request $request, Application $app) { 
    ... 

    $path = APP_ROOT . '/../web'; 

    ... 
}