如何在课堂上访问 Laravel Singletons?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35684830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access Laravel Singletons in a class?
提问by Yahya Uddin
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)
但是,我似乎无法在其他自定义类(即非控制器类)中访问此单例。( 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
.
请注意,我将创建Bar
.
回答by nCrazed
Type-hint the class/interface in your constructor and in most cases Laravel will automatically resolve and inject it into you class.
在你的构造函数中输入类/接口的类型提示,在大多数情况下,Laravel 会自动解析并将其注入你的类中。
See the Service Provider documentationfor 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:
如果Bar::__construct
需要在服务提供者中无法定义的其他参数,您将不得不使用服务定位器:
/* $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);
}
}
回答by Marcin Nabia?ek
You can use singleton running make
method of Application this way:
您可以通过make
这种方式使用Application 的单例运行方法:
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.
您可以在容器解析文档中阅读有关此内容的更多信息。