Silex将app和请求传递给控制器​​类

时间:2013-07-10 04:35:27

标签: silex

我想要一种简单的方法来访问我的控制器类中的$ app和$ request。该文件说要做到这一点,

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

但是向每个方法注入$ app和$ request似乎并不正确。有没有办法默认包含$ app和$ request到每个控制器,也许使用构造函数?我希望能够将它用作$ this-> app。

感谢。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

有可能:

在项目的某处创建一个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');
    }
}