thinkphp6: 自定义常量(php 8.1.1 / thinkphp v6.0.10LTS )
一,编写php代码
1,config/errorMsg.php 代码:<?php //user define('USER_NOT_EXIST', ['code'=>1001,'msg'=>'用户不存在']); define('USER_NOT_ACTIVE', ['code'=>1002,'msg'=>'用户未激活']); return [ '0' => '成功', '1000' => '不存在的请求地址', '1001' => '用户名不存在', '1002' => '用户未激活', ];2,result/Result.php
<?php namespace app\result; use think\response\Json; class Result { //success,返回数据 static public function Success($data):Json { $rs = [ 'code'=>0, 'msg'=>"success", 'data'=>$data, ]; return json($rs); } //error需要code/msg参数 static public function ErrorCode($code,$msg):Json { $rs = [ 'code'=>$code, 'msg'=>$msg, 'data'=>"", ]; return json($rs); } //error,传入定义的数组常量 static public function Error($arr):Json { $rs = [ 'code'=>$arr['code'], 'msg'=>$arr['msg'], 'data'=>"", ]; return json($rs); } }3,controller/Goods.php 使用常量
class Goods extends BaseController { /** * 商品详情 * * @return \think\Response */ public function Detail(){ //return Result::Error(USER_NOT_EXIST); return Result::Error(USER_NOT_ACTIVE); } }
说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,测试效果
三,查看php和thinkphp的版本:
php:liuhongdi@lhdpc:/data/php/admapi$ php --version PHP 8.1.1 (cli) (built: Dec 20 2021 16:12:16) (NTS) Copyright (c) The PHP Group Zend Engine v4.1.1, Copyright (c) Zend Technologies with Zend OPcache v8.1.1, Copyright (c), by Zend Technologiesthinkphp:
liuhongdi@lhdpc:/var/www/html$ cd /data/php/admapi/ liuhongdi@lhdpc:/data/php/admapi$ php think version v6.0.10LTS