0

My question is: How can I use laravel service containers to do heavy tasks. Actually I would like to use service containers to increase the performance.

Suppose we have the below class:

class HeavyTask
{
    public function doHeavyTasks(){

    }
}

and we define a service container for this class:

$this->app->singleton('HeavyTask' , function($app){
    return new HeavyTask();
});

Suppose the class HeavyTask is going to call too many api requests.

I will be thankful if you give me an example how can I call these requests api with a better performance. If we would like to define a scheduled task How can we do this?

$schedule->call(function(){
    // do scheduled task
})->daily();

and I'll be thankful if you say what is the difference between the scenario we haven't used service container and the scenario we will use service container?(the difference between these two states performance)

farhad.a
  • 341
  • 4
  • 17
  • Thanks for your response. My question is about how the service containers help me to have a better performance in heavy tasks. and how can I write the code related to `HeavyTask` class in `app/Console/Kernel.php` file? – farhad.a Aug 28 '23 at 01:17
  • My bad I think I misinterpreted what service container was. Upon reading the docs, it is about using classB inside classA. There are a lot of ways to do this. One is to use dependency injection. Calling classB inside the construct of classA so that you can use classB – Mr. Kenneth Aug 28 '23 at 01:46
  • If you check https://laravel.com/docs/10.x/container#introduction, `UserController` is using the class of `UserRepository` by adding it in the `__construct` – Mr. Kenneth Aug 28 '23 at 01:47
  • Because of that, the methods of `UserController` can now use the `UserRepository` methods by using the variable `$this->user`. – Mr. Kenneth Aug 28 '23 at 01:49
  • Though I would prefer to add a `protected $user` before the `construct` then do `function __construct(UserRepository $user) {$this->user = $user}` – Mr. Kenneth Aug 28 '23 at 01:50
  • 1
    Simple answer - SC is not for performance, it’s for dependency injection. – Maksim Aug 28 '23 at 08:56

0 Answers0