我在 Slim 3 MVC 框架中构建我的网站。我需要为控制器调用一些常用的函数(例如:对于页面标题的别名,我正在使用一个名为的函数function getAlias(){.....}
)。
我必须在哪里创建这些功能?如何调用内部控制器?
有很多方法可以做到这一点。如果这些函数没有副作用,那么一种选择是拥有一个包含静态方法的实用程序类。
另一种选择是从一个公共类扩展所有路由操作并使用它:
// CommonAction.php
class CommonAction
{
protected function getAlias() { }
}
// HomeAction.php
class HomeAction extends CommonAction
{
public function __construct(/*dependencies here*/) { }
public function __invoke($request, $response, $args) {
// route action code here
return $response;
}
}
// index.php
$app = new Slim\App(require('settings.php'));
$container = $app->getContainer();
$container[HomeAction::class] = function ($c) {
return new HomeAction(/*dependencies*/);
}
$app->get('/', HomeAction::class);
$app->run();
如果该功能是您的域层的一部分,则将这些类作为依赖项注入到您的路由操作中。