0

I make a "HelperCommand" to generate helper in Laravel. "HelperCommand" will create a file in "app/Console/Commands/Helpers".

php artisan helper:command 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 :

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

My question is how to automatically add autoload when generating helper?

thanks!

Briel
  • 150
  • 7
  • Depends, what do these files do? Are they php classes? Do they contain functions? Are they just data files? – Jerodev Feb 05 '20 at 16:08
  • Also, take a look at this question: https://stackoverflow.com/questions/26174024/composer-autoload-multiple-files-in-folder – Jerodev Feb 05 '20 at 16:10
  • This is php file php artisan helper:command time.php create a new file named time.php – Briel Feb 05 '20 at 16:18
  • Why should that be needed? Where is this file placed? Shouldn't the regular autoloader cover that namespace properly? Have you ever felt the need to add specific classes manually to that list? – Nico Haase Feb 08 '20 at 20:10

1 Answers1

0

You can modify composer.json in various ways.

Not recommended

One simple way is to use file_get_contents () and 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

Recommendation

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. You can see the technique that I used there.

Wahyu Kristianto
  • 8,719
  • 6
  • 43
  • 68
  • {"name":"laravel\/laravel","type":"project","description":"The Laravel Framework.","keywords":["framework","laravel"],"license":"MIT"..... how to make it pretty? – Briel Feb 05 '20 at 16:23
  • You can use `JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT`. I will update my answer – Wahyu Kristianto Feb 05 '20 at 16:27