为控制器中所有操作添加 class 到头部导航栏。
代码示例:
class UserController extends Controller
{
public function __construct()
{
// 为所有操作添加 class 到头部导航栏
$this->middleware(function ($request, $next) {
$controller = $request->route()->getAction()['controller'];
list($controller, $action) = explode('@', $controller);
$navClass = $this->getNavClass($controller, $action);
view()->share('navClass', $navClass);
return $next($request);
});
}
/**
* 获取导航栏 class。
*/
private function getNavClass($controller, $action)
{
// 根据控制器和操作获取相应的 class
if ($controller === 'HomeController') {
if ($action === 'index') {
return 'active';
}
} elseif ($controller === 'UserController') {
if ($action === 'index') {
return 'active';
}
}
return '';
}
// ...
}