Ad

Automatically Add Autoload

- 1 answer

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!

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad