鍍金池/ 問答/PHP/ laravel 5想自定義全局函數(shù),怎么弄呢?

laravel 5想自定義全局函數(shù),怎么弄呢?

想把

//生成友好時間形式
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;
    }
}

放入函數(shù)庫,怎么放呢

回答
編輯回答
挽青絲
2018年8月18日 18:31
編輯回答
熟稔

參考:laravel5.*添加創(chuàng)建自定義全局函數(shù)(輔助函數(shù)) https://phpartisan.cn/news/76...

2017年6月26日 13:01
編輯回答
嫑吢丕

在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"
    ]
},

...

然后執(zhí)行:

composer dump-auto
2017年5月3日 15:05