php - laravel 5想自定义全局函数,怎么弄呢?

查看:68
本文介绍了php - laravel 5想自定义全局函数,怎么弄呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

想把

//生成友好时间形式
function  friendly_date( $from ){
    static $now = NULL;
    $now == NULL && $now = time();
    ! is_numeric( $from ) && $from = strtotime( $from );
    $seconds = $now - $from;
    $minutes = floor( $seconds / 60 );
    $hours   = floor( $seconds / 3600 );
    $day     = round( ( strtotime( date( 'Y-m-d', $now ) ) - strtotime( date( 'Y-m-d', $from ) ) ) / 86400 );
    if( $seconds == 0 ){
        return '刚刚';
    }
    if( ( $seconds >= 0 ) && ( $seconds <= 60 ) ){
        return "{$seconds}秒前";
    }
    if( ( $minutes >= 0 ) && ( $minutes <= 60 ) ){
        return "{$minutes}分钟前";
    }
    if( ( $hours >= 0 ) && ( $hours <= 24 ) ){
        return "{$hours}小时前";
    }
    if( ( date( 'Y' ) - date( 'Y', $from ) ) > 0 ) {
        return date( 'Y-m-d', $from );
    }
    
    switch( $day ){
        case 0:
            return date( '今天H:i', $from );
        break;
        
        case 1:
            return date( '昨天H:i', $from );
        break;
        
        default:
            //$day += 1;
            return "{$day} 天前";
        break;
    }
}

放入函数库,怎么放呢

解决方案

在app/Helpers/(目录可以自己随便来) 下新建一个文件 functions.php
在functions.php 中加入这个方法
然后在
bootstrap/autoload.php 中添加

require __DIR__.'/../app/Helpers/functions.php';

或者在
composer.json 中的 autoload 下增加

"files": [
    "app/Helpers/functions.php"
]

...
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/helpers/functions.php"
    ]
},

...

然后执行:

composer dump-auto

这篇关于php - laravel 5想自定义全局函数,怎么弄呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆