How to access Laravel Singletons in a class?
Type-hint the class/interface in your constructor and in most cases Laravel will automatically resolve and inject it into you class.
See the Service Provider documentation for some examples and alternatives.
To go with your example:
class Bar {
private $myClass;
public function __construct(MyClass $myClass) {
$this->myClass = $myClass;
}
}
In cases where Bar::__construct
takes other parameters that can not be per-defined in a service provider you will have to use a service locator:
/* $this->app is an instance of Illuminate\Foundation\Application */
$bar = new Bar($this->app->make(MyClass::class), /* other parameters */);
Alternatively, move the service location into the constructor it self:
use Illuminate\Support\Facades\App;
class Bar {
private $myClass;
public function __construct() {
$this->myClass = App::make(MyClass::class);
}
}
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);
}
}
You can use singleton running make
method of Application this way:
use Illuminate\Contracts\Foundation\Application;
class Bar {
private $myClass;
private $a;
private $b;
public function __construct($a, $b, Application $app) {
$this->a = $a;
$this->b = $b;
$this->myClass = $app->make(MyClass::class);
}
}
You can read more about this in Container resolving documentation.