laravel:自定义常量/公共函数(10.27.0)

一,配置:

1,在bootstrap/app.php中添加两行:

1
2
3
4
// 常量定义文件
require __DIR__ . '/const.php';
// 公共函数定义文件
require __DIR__ . '/function.php';

二,php代码

1,自定义常量:bootstrap/const.php

1
2
3
4
5
6
7
<?php
//提示信息
define('SITE_NAME', "laravel教学站");
//用户不存在
define('USER_NOT_EXIST', ['code'=>1001,'msg'=>'用户不存在']);
//用户未激活
define('USER_NOT_ACTIVE', ['code'=>1002,'msg'=>'用户未激活']);

2, 自定义公共函数:bootstrap/function.php

1
2
3
4
5
6
7
8
9
<?php
//返回网站的信息
function getSiteInfo() {
    $arr = [
        "name"=>"php教学站",
        "host"=>"www.liuhongdi.com",
    ];
    return $arr;
}

3,在controller中的调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
 * 使用自定义的常量或函数
 * */
public function useconst(Request $request) {
    //打印自定义常量
    $arr = USER_NOT_ACTIVE;
    $code = $arr['code'];
    $msg = $arr['msg'];
 
    echo "code:".$code.":<br/>";
    echo "msg:".$msg.":<br/>";
    echo "站点名称:".SITE_NAME.":<br/>";
    //打印自定义函数的返回
    $siteArr = getSiteInfo();
    var_dump($siteArr);
}

说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/11/01/laravel-zi-ding-yi-chang-liang-gong-gong-han-shu-10-27/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com

三,查看效果:

四,查看laravel框架的版本:

liuhongdi@lhdpc:/data/laravel/dignews$ php artisan --version
Laravel Framework 10.27.0
posted @ 2023-11-02 07:52  刘宏缔的架构森林  阅读(123)  评论(0编辑  收藏  举报