0

I have function in a Controller, and I want that function to execute according to some randomly set cron jobs. I would like to know how to run a Controller function inside an Artisan Command.

I already saw this link: Laravel 5 - how to run a Controller method from an Artisan Command?

But to me it doesn't seem like the safest/best way to do this. Has anybody done this before?

Community
  • 1
  • 1
Adam Silva
  • 1,013
  • 18
  • 48
  • Why would you want to put this method in your controller? You could make a console command which the cronjob executes? –  May 15 '17 at 10:17

1 Answers1

0

Maybe you could make through app() an instance of your controller and call its method?

Example: app()->make(\App\Http\Controllers\UserController::class)->someMethod();

BUT.. This is not the right way. For me the right way is to put your method's logic into a registered service from your app and to call it both in the controller and in your command:

class CronJobService
{
    public function handle($something)
    {
        // Do stuff...
    }
}

class UserController
{
    public function runCronJobs(CronJobService $cronjob)
    {
        $cronjob->handle($something);
    }
}

class MyRandomCommand
{
    public function __construct(CronJobService $cronjob)
    {
        $this->cronjob = $cronjob;
    }

    public function handle()
    {
        $this->cronjob($something)
    }
}
everytimeicob
  • 327
  • 2
  • 10