How To Dynamically Register Commands And Schedulers In Laravel 5?

- 1 answer

I am working on a composer package which is used by multiple laravel 5 application so I have a service provider in there which hooks the goodies into laravel 5 application when installed in one.

I know I can register service providers for dependent packages like so:


I know I can also load aliases like so:

$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('Excel', 'Maatwebsite\Excel\Facades\Excel');
$loader->alias('Firewall', 'PragmaRX\Firewall\Vendor\Laravel\Facade');

But what about registering commands and schedule calls? Are there methods to do that too? If yes, how do I do it?

I am newbie trying to learn good OOP practices and I get stuck in such things. So more importantly, where do I go looking for such stuff? Is there documentation for this too? Because I couldn't find this stuff in the Package Development section at laravel.



The Service Provider has a commands() method that will register a command with artisan. You can use it like so:

public function register()
    $this->app->singleton('command.goodies.yourcommand', function ($app) {
        return $app['Your\Namespace\Commands\YourCommand'];

As far as setting a scheduled task, I don't believe that can (or should) be done from your package. Registering the command gives the user the tool to use. However, scheduling the task is trying to use the tool for them. That should be left up to the user to do.

Your best bet is to be very clear in your documentation on how to schedule the task and what your recommendations may be. The "how-to" should also include entering the cron job, as this may be the user's first time setting up a scheduled task.