這是可能的:
在你的項目中創建一個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');
}
}
我嘗試使用控制器服務,但我不能注入的請求。我試過這個... $ app ['posts.controller'] = $ app-> share(function(Request $ request)use($ app){ return new PostController($ app,$ request); }); – tdbui22
通過'$ app [「request」]訪問請求。 – Maerlyn
只是一個小方面的說明:在Silex 2.X'$ app ['request']'改爲'$ app ['request_stack'] - > getCurrentRequest()' – Davincho