中间件
在执行主要逻辑之前进行某些操作或之后进行某些操作 常用来登录验证,csrf验证等
中间件创建
php think make:middleware stop
全局中间件
写在根目录的middleware.php中 对全局有效 app/middleware.php
return [
];
应用中间件
写在应用的middleware.php中 对当前应用有效 app/admin/middleware.php
return [
\think\middleware\SessionInit::class
];
路由中间件
写在路由文件中 针对指定的路由有效
use think\facade\Route;
Route::any('test', 'base.home/test')->middleware(\app\middleware\stop::class);
Route::group(function () {
Route::any('home', 'base.home/index');
Route::any('look', 'base.home/look');
})->middleware(\app\middleware\stop::class);
控制器中间件
namespace app\admin\controller\base;
use app\BaseController;
use app\middleware\stop;
use app\Request;
use think\App;
class Home extends BaseController
{
public function initialize()
{
$this->middleware = [stop::class => ['only' => 'index']];
}
public function index()
{
return captcha('verify');
}
public function test(Request $request)
{
return json(['name' => 'name'], 200, ['content-type' => 'text/json']);
}
}
视图
引入视图组件
composer require topthink/think-view
渲染视图
namespace app\admin\controller\base;
use app\BaseController;
use think\App;
use think\facade\View;
class Home extends BaseController
{
public function index()
{
return View::fetch('index');
}
}
使用绝对路径渲染模版
namespace app\admin\controller\base;
use app\BaseController;
use think\App;
use think\facade\View;
class Home extends BaseController
{
public function index()
{
return View::fetch(rtrim(root_path('view/common/index.php'), '/'));
}
}
模版传参
namespace app\admin\controller\base;
use app\BaseController;
use think\App;
use think\facade\View;
class Home extends BaseController
{
public function index()
{
return View::fetch('/index', ['name' => 'this is name']);
}
}
viwe 辅助函数
view辅助函数是在对View 视图的封装 提供了常用的参数设置 view(string $template = ‘’, $vars = [], $code = 200, $filter = null) $template 模版地址 同 View::fetch() 中的模版地址用法相同 $vars 模版传参 同 View::fetch() 中的模版传参相同 $code 设置响应状态码 $filter 闭包函数,对最后输出的内容进行处理
namespace app\admin\controller\base;
use app\BaseController;
use think\App;
class Home extends BaseController
{
public function index()
{
return view('/index', ['name' => 'this is name'], 200, function ($content) {
return "a" . $content . "b";
});
}
}
|