Laravel 添加自定义全局函数

来源:互联网 发布:网络投影机办公 编辑:程序博客网 时间:2024/05/13 08:50

第一步:在app目录下建立Common文件夹,在文件夹中创建helpers.php

第二步:在artisan中引入require __DIR__.'/app/Common/helpers.php';自动加载

第三步:在public目录下的index.php文件中加入require __DIR__.'/../app/Common/helpers.php';

此时你可以在任意类,模板中使用自定义方法:

例:

<?php


namespace {


    use Illuminate\Support\Debug\Dumper;
    use Illuminate\Container\Container;


    if (!function_exists('is_wechat')) {
        function is_wechat()
        {
            $result = isset($_SERVER['HTTP_USER_AGENT']) ?
                strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') : false;
            return $result !== false;
        }
    }


    if (!function_exists('dump')) {
        function dump()
        {
            array_map(function ($x) {
                (new Dumper)->dump($x);
            }, func_get_args());
        }
    }


    if (!function_exists('db_escape')) {
        function db_escape($value, $escape_char = '\\', $charsets = ['%', '_'])
        {
            $escaped = [];


            foreach ($charsets as $c) {
                $escaped[$c] = $escape_char . $c;
            }
            //$escaped[$escape_char] = $escape_char . $escape_char;


            return strtr($value, $escaped);
        }
    }


    if (!function_exists('asset')) {
        function asset($path, $secure = null)
        {
            $pathinfo = pathinfo($path);
            if ($pathinfo && isset($pathinfo['extension']) && ('css' === $pathinfo['extension'])) {
                $appVersion = Container::getInstance()->make('config')->get('config.app_version', time());


                $path .= "?_v=$appVersion";
            }


            return Container::getInstance()->make('url')->asset($path, $secure);
        }
    }


    if (!function_exists('format_json_success')) {
        function format_json_success($body = null)
        {
            return array(
                'body' => $body,
                'status' => 'SUCCESS',
            );
        }
    }


    if (!function_exists('format_json_failed')) {
        function format_json_failed($error = 'internal_error', $data = [], $status = 'FAILED')
        {
            $error = trans()->has('errors.' . $error) ? trans('errors.' . $error) : $error;
            $body = array_merge(['error' => $error], $data);
            return array(
                'body' => $body,
                'status' => $status,
            );
        }
    }


    if (!function_exists('get_ip')) {
        function get_ip($ip2long = false)
        {
            $ip = null;
            if (!$ip && getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
                $ip = getenv('HTTP_CLIENT_IP');
            }
            if (!$ip && getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
                $ips = explode(',', getenv('HTTP_X_FORWARDED_FOR'));
                if (count($ips) > 0) {
                    $ip = trim($ips[0]);
                }
            }
            if (!$ip && getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
                $ip = getenv('REMOTE_ADDR');
            }
            if (!$ip && isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
            if (!$ip) {
                $ip = "0.0.0.0";
            }


            return $ip2long ? ip2long($ip) : $ip;
        }
    }


    if (!function_exists('format_currency')) {
        function format_currency($amount, $decimals = 2, $dec_point = '.' , $thousands_sep = ',')
        {
            return number_format($amount, $decimals, $dec_point, $thousands_sep);
        }
    }


    if (!function_exists('now')) {
        function now()
        {
            return date('Y-m-d H:i:s');
        }
    }


    if (!function_exists('json_encode_unicode')) {
        function json_encode_unicode($data, $options = 0)
        {
            if (defined('JSON_UNESCAPED_UNICODE')) {
                return json_encode($data, JSON_UNESCAPED_UNICODE | $options);
            }


            return preg_replace_callback('/(?<!\\\\)\\\\u([0-9a-f]{4})/i',
                function ($m) {
                    $d = pack('H*', $m[1]);
                    $r = mb_convert_encoding($d, 'UTF8', 'UTF-16BE');
                    return $r !== "?" && $r !== "" ? $r : $m[0];
                }, json_encode($data, $options)
            );
        }
    }
}


namespace Api {


    function format_json_success($body = null)
    {
        return $body;
    }


    function format_json_failed($code, $error = '', $data = [])
    {
        if (!$error) {
            $error = trans()->has('errors.code.' . $code)
                ? trans('errors.code.' . $code)
                : trans('errors.internal_error');
        } else {
            $error = trans()->has('errors.' . $error)
                ? trans('errors.' . $error)
                : $error;
        }


        $body = [
            'code' => $code,
            'message' => $error,
        ];
        $body = array_merge($body, $data);
        return $body;
    }


    function is_mobile($value)
    {
        return preg_match('/^1\d{10}$/', $value);
    }


    function date_format($date, $format = 'Y-m-d H:m:s')
    {
        return $date ? $date->format($format) : '';
    }
}

0 0