以下内容基于开发文档进行解析
官方文档:序言 - ThinkPHP官方手册
一 基础
1 安装
使用composer安装开发版(最新版)
composer create-project topthink/think tp
启动环境变量
在根目录下有一个文件.example.env,可以将其修改为.env生效
其中APP_DEBUG为调试模式,当运行出现异常时会显示具体异常信息,上线部署后需要关闭
APP_DEBUG = true
运行项目
php think run
出现下图表现运行成功
在浏览器中输入
http://localhost:8000/
二 架构
1 多模块和多应用
开启多模块
在route/app.php最后添加一行代码
// 开启多模块URL自动解析 `8.1+`版本开始支持
Route::auto();
默认的URL解析规则更改为
https://domainName/moduleName/controllerName/actionName
例如
https://www.test.com/admin/index/index
开启多应用
安装多应用模式扩展
composer require topthink/think-multi-app
创建模块
php think build admin
删除app下的controller文件夹
2 容器和依赖注入
依赖注入其实本质上是指对类的依赖通过构造器完成自动注入
系统内置的常见类有
系统类库 | 容器绑定标识 |
think\App | app |
think\Cache | cache |
think\Config | config |
think\Db | db |
think\Env | env |
think\Http | http |
think\Middleware | middleware |
think\Request | requrst |
think\Validate | validate |
在app/provider.php容器中添加类
return [
'think\Request' => Request::class,
'think\exception\Handle' => ExceptionHandle::class,
'api'=>\app\api\controller\Index::class
];
调用容器内类的方法
$name = app()->config->get('app_name');
return app('api')->index();
也可以携带参数
$cache = app('cache',['file']);
3 中间件
生成中间件
php think make:middleware Check
这个指令会 app/middleware
目录下面生成一个Check
中间件
<?php
namespace app\middleware;
class Check
{
public function handle($request, \Closure $next)
{
if ($request->param('name') == 'think') {
return redirect('/api/index/index');
}
return $next($request);
}
}
注意:
- 中间件的入口执行方法必须是
handle
方法,而且第一个参数是Request
对象,第二个参数是一个闭包。- 中间件
handle
方法的返回值必须是一个Response
对象。
配置中间件config/middleware.php
return [
// 别名或分组
'alias' => [
'check' => app\middleware\Check::class,
],
// 优先级设置,此数组中的中间件会按照数组中的顺序优先执行
'priority' => [],
];
配置全局中间件app/middleware.php
return [
// 其他配置...
'check',
];
配置route/app.php,在经过该路由时调用中间件
use think\facade\Route;
Route::get('admin/index/index', [\app\admin\controller\Index::class, 'index'])
->middleware('check');
或者不用配置route/app.php
直接在需要中间件的类上添加属性
缺点:该类上的所有方法都会调用中间件
protected $middleware = ['check'];