我有的:
# 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' }
如何访问控制器中的 $app 实例?这很简单:
# 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
...
那么,哪种方式更适合将 silex $app 注入 Base Controller?