2013-07-10 116 views
7

我想要一个简单的方法来访问我的控制器类中的$ app和$ request。该文件说这样做,Silex将应用程序和请求传递给控制器​​类

public function action(Application $app, Request $request) { 
// Do something. 
} 

但它看起来不正确的必须注入$ app和$请求到每个方法。有没有办法在默认情况下将$ app和$ request包含到每个控制器,也许使用构造函数?我希望能够以$ this-> app的形式使用它。

谢谢。

回答

3

Controllers as Services文档的一部分中,您可以看到如何通过构造函数向控制器类注入依赖项 - 在这种情况下是存储库。

+0

我尝试使用控制器服务,但我不能注入的请求。我试过这个... $ app ['posts.controller'] = $ app-> share(function(Request $ request)use($ app){ return new PostController($ app,$ request); }); – tdbui22

+7

通过'$ app [“request”]访问请求。 – Maerlyn

+10

只是一个小方面的说明:在Silex 2.X'$ app ['request']'改为'$ app ['request_stack'] - > getCurrentRequest()' – Davincho

0

这是可能的:

在你的项目中创建一个ControllerResolver.php的地方,并把这个里面:

namespace MyProject; 

use Silex\ControllerResolver as BaseControllerResolver; 

class ControllerResolver extends BaseControllerResolver 
{ 
    protected function instantiateController($class) 
    { 
     return new $class($this->app); 
    } 
} 

然后将其注册在您的应用程序($app->run();前):

$app['resolver'] = function ($app) { 
    return new \MyProject\ControllerResolver($app, $app['logger']); 
}; 

现在你可以为您的应用程序创建一个基本控制器,例如:

namespace MyProject; 

use Silex\Application; 
use Symfony\Component\HttpFoundation\Response; 

abstract class BaseController 
{ 
    public $app; 

    public function __construct(Application $app) 
    { 
     $this->app = $app; 
    } 

    public function getParam($key) 
    { 
     $postParams = $this->app['request_stack']->getCurrentRequest()->request->all(); 
     $getParams = $this->app['request_stack']->getCurrentRequest()->query->all(); 

     if (isset($postParams[$key])) { 
      return $postParams[$key]; 
     } elseif (isset($getParams[$key])) { 
      return $getParams[$key]; 
     } else { 
      return null; 
     } 
    } 

    public function render($view, array $parameters = array()) 
    { 
     $response = new Response(); 
     return $response->setContent($this->app['twig']->render($view, $parameters)); 
    } 

} 

并且将其扩展:

class HomeController extends BaseController 
{ 
    public function indexAction() 
    { 
     // now you can use $this->app 

     return $this->render('home.html.twig'); 
    } 
} 
相关问题