在写项目的时候偶尔会加载一些不需要传递参数的静态视图,例如
class Index extends Common
{
public function index()
{
return $this->fetch();
}
public function top()
{
return $this->fetch();
}
public function menu()
{
return $this->fetch('',['menus'=>$this->_user['menus']]);
}
public function main()
{
return $this->fetch();
}
public function flush()
{
$user_info = Db::name('admin')->select();
foreach($user_info as $v){
cache('user_info_id_'.$v['id'],null);
}
}
}
这种代码重复率太高,不够优雅。我们可以将创建一个单独的方法,专门用来加载这种没有数据交互的静态视图,以提高代码的利用率。这里利用到tp5不需要存在同名方法就可以直接调用视图的这一特性,代码如下
public function route(){
/**
* 传入action参数即可访问相应控制器
*/
$action = input('action','index');
return $this->fetch($action);
}
想要加载这些页面时可以调用route方法,传递要访问的静态页面的名字即可。
//调用案例一、在生成url时传入参数
{:url('index/route','index')}
//调用案例二、在跳转时传递参数
$this->success('index/route','index');