是的,这很容易,这是我在最近的一个项目中采取的步骤。
首先假设你有一个 HomeActionController
class HomeActionController {
//The below line I have moved into an abstract Controller class
public $view = null;
//This is using Slim Views PhpRenderer
//This allows for a controller to render views can be whatever you need
//I did not like the idea of passing the whole DC it seemed overkill
//The below method I have moved into an abstract Controller class
public function __construct(\Slim\Views\PhpRenderer $view = null){
if($view != null){
$this->view = $view;
}
}
//View could be any action method you want to call it.
public function view(Request $request, Response $response, array $args){
$data['user'] = "John Doe";
return $this->view->render($response, 'templates/home.php', $data);
}
}
现在您需要能够从路由中调用此控制器的实例,因此您需要将您拥有的控制器添加到 DC
无论您在何处创建 slim 实例,都需要获取 DC 并添加控制器实例:
$app = new \Slim\App($config['slim']);
// Get Dependency Container for Slim
$container = $app->getContainer();
$container['HomeActionController'] = new Controller\HomeActionController($container['view']); //Notice passing the view
作为说明,上述实例化可能是一个闭包,但我当时没有看到或制作它们。此外,还有一些我尚未探索过的延迟加载方法,请参阅here 了解更多信息。
现在您需要做的最后一件事是能够在路线上调用这些,这并不是一个巨大的挑战。
$app->get('/home', 'HomeActionController:view');
当然,您不能对参数进行操作,但我没有遇到问题,只是在请求中传递它们,然后从那里获取它们。