Home  >  Article  >  PHP Framework  >  Analyze how Thinkphp5 realizes front-end and back-end separation

Analyze how Thinkphp5 realizes front-end and back-end separation

藏色散人
藏色散人forward
2021-05-20 15:31:144284browse

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(&#39;Access-Control-Allow-Origin: *&#39;);
        header("Access-Control-Allow-Headers: token,Origin, X-Requested-With, X_Requested_With,Content-Type, Accept");
        header(&#39;Access-Control-Allow-Methods: POST,GET,PUT&#39;);
        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

// 默认输出类型
    &#39;default_return_type&#39;    => &#39;json&#39;,

When returning data after modification, you can directly return the following

  return [&#39;code&#39;=>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 = &#39;&#39;;
    private $errline = &#39;&#39;;
    private $errtrace = &#39;&#39;;
    private $errtracestring = &#39;&#39;;
    protected function getSourceCode(Exception $exception)
    {
        // 读取前9行和后9行
        $line  = $exception->getLine();
        $first = ($line - 9 > 0) ? $line - 9 : 1;

        try {
            $contents = file($exception->getFile());
            $source   = [
                &#39;first&#39;  => $first,
                &#39;source&#39; => array_slice($contents, $first - 1, 19),
            ];
        } catch (Exception $e) {
            $source = [&#39;code&#39;=>1];
        }
        return $source;
    }
    public function render(Exception $e)
    {
        $app_debug = Env::get(&#39;APP_DEBUG&#39;);
        //如果是调试模式
        if($app_debug)
        {
            $this->msg = $e->getMessage();
            $this->errCode = $e->getCode();
            $this->errFile = json($this->getSourceCode($e));
            $this->errline = $e->getLine();
            if(Env::get(&#39;APP_TRACE&#39;))
            {
                $this->errtrace = $e->getTrace();
                $this->errtracestring = $e->getTraceAsString();
            }
        }
        else
        {
            $result = [
                &#39;msg&#39; => $e->getMessage(),
                &#39;errFile&#39; => ($this->getSourceCode($e)),

                &#39;code&#39; => 999,
            ];
            return json($result);
        }
        return json([
            &#39;code&#39;=>$this->code,
            &#39;msg&#39;=>$this->msg,
            &#39;errCode&#39;=>$this->errCode,
            &#39;errFile&#39;=>$this->errFile,
            &#39;errLine&#39;=>$this->errline,
            &#39;errtrace&#39;=>$this->errtrace,
            &#39;errtracestring&#39;=>$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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete