Search code examples
phplaravellaravel-5service-provider

How to access Laravel Singletons in a class?


I have registered a singleton in a service provider like so:

$this->app->singleton(MyClass::class);

This can normally be accessed by simply stating it in the parameters like so:

class FooController extends Controller
{
    public function index(MyClass $myClass)
    {
        //...
    }
}

However I cannot seem to be able to access this singleton in other custom classes (i.e. non controller classes). (https://laravel.com/docs/5.2/container#resolving)

For example like here:

class Bar {
   private $myClass;
   private $a;
   private $b;

   public function __construct($a, $b) {
      $this->a = $a;
      $this->b = $b;
      $this->myClass = ... // TODO: get singleton
   }
}

How do I do this?

Note that I will be creating multiple instances of Bar.


Solution

  • In later Laravel versions 6 and higher there are even more helpers to solve this:

    resolve(MyClass::class);
    app(MyClass::class);
    

    & all the methods provided by the other answers

    class Bar {
       private $myClass;
       private $a;
       private $b;
    
       public function __construct($a, $b) {
          $this->a = $a;
          $this->b = $b;
          $this->myClass = app(MyClass::class);
       }
    }