如果需要定义全局方法和全局常量,自己摸索了一点方法:
1、在bootstrap目录中,或者任意你喜欢的位置创建public.php,里面编写你的全局方法
<?php
// 生成一个随机的用户名
if (! function_exists('generate_username')) {
function generate_username() {
return str_random(16);
}
}
2、在composer.json中的autoload中添加files
"autoload": {
"files": [
"bootstrap/public.php" //这里指向全局方法或全局常量代码文件
]
},
3、重新生成autoload
composer dumpautoload
4、检查vendor/composer/autoload_files.php,发现文件public.php已经自动加载
return array(
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'667aeda72477189d0494fecd327c3641' => $vendorDir . '/symfony/var-dumper/Resources/functions/dump.php',
'5255c38a0faeba867671b61dfda6d864' => $vendorDir . '/paragonie/random_compat/lib/random.php',
'72579e7bd17821bb1321b87411366eae' => $vendorDir . '/illuminate/support/helpers.php',
'1d1b89d124cc9cb8219922c9d5569199' => $vendorDir . '/hamcrest/hamcrest-php/hamcrest/Hamcrest.php',
'2c102faa651ef8ea5874edb585946bce' => $vendorDir . '/swiftmailer/swiftmailer/lib/swift_required.php',
'c964ee0ededf28c96ebd9db5099ef910' => $vendorDir . '/guzzlehttp/promises/src/functions_include.php',
'a0edc8309cc5e1d60e3047b5df6b7052' => $vendorDir . '/guzzlehttp/psr7/src/functions_include.php',
'e7223560d890eab89cda23685e711e2c' => $vendorDir . '/psy/psysh/src/Psy/functions.php',
'decc78cc4436b1292c6c0d151b19445c' => $vendorDir . '/phpseclib/phpseclib/phpseclib/bootstrap.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php',
'f0906e6318348a765ffb6eb24e0d0938' => $vendorDir . '/laravel/framework/src/Illuminate/Foundation/helpers.php',
'58571171fd5812e6e447dce228f52f4d' => $vendorDir . '/laravel/framework/src/Illuminate/Support/helpers.php',
'f4efd79f57e8418cfb06b27ba8753cd5' => $baseDir . '/bootstrap/public.php', //我们的文件
);
4、可以在代码里任何地方使用此方法了
Route::get('/username', function () {
return generate_username();
});