[英]Automatically add autoload
I make a "HelperCommand" to generate helper in Laravel.我制作了一个“HelperCommand”来在 Laravel 中生成助手。 "HelperCommand" will create a file in "app/Console/Commands/Helpers".
“HelperCommand”将在“app/Console/Commands/Helpers”中创建一个文件。
php artisan helper:command time.php
php 工匠助手:命令 time.php
public function handle()
{
$name = $this->argument('name');
File::put(app_path().'/Console/Commands/Helpers/'.$name, '');
}
I manually add file name in composer.json :我在 composer.json 中手动添加文件名:
"autoload": {
"files": [
"app/Console/Commands/Helpers/time.php"
]
}
My question is how to automatically add autoload when generating helper?我的问题是如何在生成助手时自动添加自动加载?
thanks!谢谢!
You can modify composer.json
in various ways.您可以通过多种方式修改
composer.json
。
One simple way is to use file_get_contents ()
and file_put_contents ()
.一种简单的方法是使用
file_get_contents ()
和file_put_contents ()
。
$composer = file_get_contents(base_path('composer.json')); // get composer.json
$array = json_decode($composer, true); // convert to array
// Add new file
$array['autoload']['files'][] = $name;
// convert to json
$json = json_encode($array, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
file_put_contents(base_path('composer.json'), $json); // Write composer.json
But, this way is not effective , and you lose a lot of time to update the autoloader, via :但是,这种方式是无效的,你会失去很多时间来更新自动加载器,通过:
composer dump-autoload
My advice, you should make your own composer package.我的建议是,您应该制作自己的作曲家包。
In your package service provider, you can get all helpers without update the autoloader.在您的包服务提供商中,您无需更新自动加载器即可获得所有帮助程序。
$files = glob(
// app/Helpers
app_path('Helpers') . '/*.php')
);
foreach ($files as $file) {
require_once $file;
}
I am the owner of laravel-helpers
.我是
laravel-helpers
的所有者。 You can see the technique that I used there.你可以看到我在那里使用的技术。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.