我有什麼:
# index.php
$app = new Silex\Application();
... (loading routes file by YamlFileLoader) ...
$app['routes']->addCollection($loader->load('routes.yml'));
$app->run();
路由:
# routes.yml
home:
pattern:/
defaults: { _controller: 'Controllers\DefaultController::indexAction' }
我怎樣才能獲取內幕控制器$應用程序實例? 很簡單:
# controllers/DefaultController.php
class DefaultController
{
public function indexAction(Request $request, Application $app)
{
// this is the place!
return $app['twig']->render('index.twig');
}
}
好吧,這很好,但也有幾個原因,這種方法是不能接受我。我想用經典的方式:
# controllers/DefaultController.php
class DefaultController
{
public function indexAction()
{
return $this->twig->render('index.twig');
}
}
爲了提供這一點,我想用父基類:
# controllers/BaseController.php
class BaseController
{
protected $twig;
public function __construct(Application $app)
{
$this->twig = $app['twig'];
}
}
正如你所期望的:
# controllers/DefaultController.php
class DefaultController extends BaseController
...
那麼,哪種方式更適合將基本控制器注入到應用程序中?
請注意,您可以將控制器定義爲服務:http://silex.sensiolabs.org/doc/providers/service_controller.html – igorw