Home >PHP Framework >ThinkPHP >Analyze how Thinkphp5 realizes front-end and back-end separation
The following thinkphp framework tutorial column will introduce to you the front-end and back-end separation of Thinkphp5. I hope it will be helpful to friends in need!
Use Thinkphp5 to implement pure API development and achieve front-end and back-end separation
The general steps are as follows
1. Domain request problem
2. Change the output data format to the commonly used API return JSON format
3. Customize exception handling (modify the adaptation API usage)
4. Start forced routing
Solving cross-domain problems
Find the application\targs.php extension definition file and modify the value of app_init
// 应用行为扩展定义文件 return [ // 应用初始化 'app_init' => [ 'app\api\Crossdomain\Cdom' ], // 应用开始 'app_begin' => [], // 模块初始化 'module_init' => [], // 操作开始执行 'action_begin' => [], // 视图内容过滤 'view_filter' => [], // 日志写入 'log_write' => [], // 应用结束 'app_end' => [], ];
In the api\Crossdomain directory of the application folder, create a new Cdom.php code in the directory file, the code is as follows
<?php namespace app\api\Crossdomain; class Cdom { public function appInit($params) { //配置IP白名单 在测试环境下可以为 * 号 生产环境下建议根据实际环境进行修改。 header('Access-Control-Allow-Origin: *'); header("Access-Control-Allow-Headers: token,Origin, X-Requested-With, X_Requested_With,Content-Type, Accept"); header('Access-Control-Allow-Methods: POST,GET,PUT'); if(request()->isOptions()){ exit(); } } }
Change the output data format to the common API return JSON format
The default output data format of TP5 is HTML, which obviously does not comply with the data specifications of the common API interfaces. Here We need to make corresponding changes. Find config.php in the application directory and modify the following configuration to avoid the need to manually json or json_encode every time
// 默认输出类型 'default_return_type' => 'json',
When returning data after modification, you can directly return the following
return ['code'=>1];
Directly output data in json format
Customized exception handling (modify the use of adaptation API)
TP5’s original exception handling mechanism will cause the request to crash directly if it is used as an API interface. In abnormal circumstances, the API interface Unable to receive normal JSON data and an error occurred. For this we need to customize the exception handling mechanism of TP.
Find the config.php configuration file in the application directory. Modify the following options to
'exception_handle' => 'app\api\Crossdomain\CdomHandle',
Find the corresponding directory, add the CdomHandle.php file, and add the following code
<?php namespace app\api\Crossdomain; use think\exception\Handle; use think\Env; use Exception; use MyCLabs\Enum\Enum; class CdomHandle extends Handle { private $code = 999; private $msg; private $errCode; private $errFile = ''; private $errline = ''; private $errtrace = ''; private $errtracestring = ''; protected function getSourceCode(Exception $exception) { // 读取前9行和后9行 $line = $exception->getLine(); $first = ($line - 9 > 0) ? $line - 9 : 1; try { $contents = file($exception->getFile()); $source = [ 'first' => $first, 'source' => array_slice($contents, $first - 1, 19), ]; } catch (Exception $e) { $source = ['code'=>1]; } return $source; } public function render(Exception $e) { $app_debug = Env::get('APP_DEBUG'); //如果是调试模式 if($app_debug) { $this->msg = $e->getMessage(); $this->errCode = $e->getCode(); $this->errFile = json($this->getSourceCode($e)); $this->errline = $e->getLine(); if(Env::get('APP_TRACE')) { $this->errtrace = $e->getTrace(); $this->errtracestring = $e->getTraceAsString(); } } else { $result = [ 'msg' => $e->getMessage(), 'errFile' => ($this->getSourceCode($e)), 'code' => 999, ]; return json($result); } return json([ 'code'=>$this->code, 'msg'=>$this->msg, 'errCode'=>$this->errCode, 'errFile'=>$this->errFile, 'errLine'=>$this->errline, 'errtrace'=>$this->errtrace, 'errtracestring'=>$this->errtracestring ]); } }
Enable strong routing
// 是否开启路由 'url_route_on' => true, // 路由使用完整匹配 'route_complete_match' => true, // 是否强制使用路由 'url_route_must' => true,
Please refer to the TP manual for Env usage here
BaseException说明:https://docs.python.org/3.1/library/exceptions.html#BaseException
Related recommendations: The latest 10 thinkphp video tutorials
The above is the detailed content of Analyze how Thinkphp5 realizes front-end and back-end separation. For more information, please follow other related articles on the PHP Chinese website!