【问题标题】:Automatically add autoload自动添加自动加载
【发布时间】:2023-03-13 07:49:01
【问题描述】:

我制作了一个“HelperCommand”来在 Laravel 中生成助手。 “HelperCommand”将在“app/Console/Commands/Helpers”中创建一个文件。

php 工匠助手:命令 time.php

public function handle()
{
    $name = $this->argument('name');
    File::put(app_path().'/Console/Commands/Helpers/'.$name, '');
}

我在 composer.json 中手动添加文件名:

"autoload": {
    "files": [
        "app/Console/Commands/Helpers/time.php"
    ]
}

我的问题是如何在生成助手时自动添加自动加载?

谢谢!

【问题讨论】:

  • 视情况而定,这些文件有什么作用?他们是php类吗?它们包含功能吗?它们只是数据文件吗?
  • 另外,看看这个问题:stackoverflow.com/questions/26174024/…
  • 这是 php 文件 php artisan helper:command time.php 创建一个名为 time.php 的新文件
  • 为什么需要这个?这个文件放在哪里?常规自动加载器不应该正确覆盖该命名空间吗?您是否觉得需要手动将特定类添加到该列表中?

标签: php json laravel composer-php


【解决方案1】:

您可以通过多种方式修改composer.json

不推荐

一种简单的方法是使用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

但是,这种方式无效,你会浪费很多时间来更新自动加载器,通过:

composer dump-autoload

推荐

我的建议,你应该制作自己的作曲家包。

在您的包服务提供者中,您可以在不更新自动加载器的情况下获取所有帮助程序。

$files = glob(
    // app/Helpers
    app_path('Helpers') . '/*.php')
);

foreach ($files as $file) {
    require_once $file;
}

我是laravel-helpers 的所有者。你可以看到我在那里使用的技术。

【讨论】:

  • {"name":"laravel\/laravel","type":"project","description":"Laravel 框架。","keywords":["framework","laravel "],"license":"MIT".....如何让它漂亮?
  • 您可以使用JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT。我会更新我的答案
猜你喜欢
  • 1970-01-01
  • 2012-12-05
  • 2017-09-02
  • 2019-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
相关资源
最近更新 更多