Parham Doustdar
Parham Doustdar

Reputation: 2039

How can I make an instance a singleton in Laravel 5.1?

In my service provider, I manually construct a service. I want to bind it into the container as a singleton. However, when I do:

$this->app->singleton('React\EventLoop\LoopInterface', $loop);

The singleton() method gets the class of $loop and attempts to create the object itself, which fails.

Upvotes: 1

Views: 553

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

In order for it to work, you'll need to pass a closure as the second argument to singleton method. If you $loop object already exists before register method is called, just do:

$loop = ...; // $loop is instantiated somewhere before this code
$this->app->singleton('React\EventLoop\LoopInterface', function() use ($loop) {
  return $loop;
});

or, if it's ok to instantiate $loop here, it's even better to do:

$this->app->singleton('React\EventLoop\LoopInterface', function() {
  $loop = ...; //instantiate $loop
  return $loop;
});

Upvotes: 1

Related Questions