我刚刚开始使用 Laravel,我真的很困惑,service contains并service providers搜索了一些示例,例如以下服务代码:
namespace App\Service;
class Tests
{
public function test()
{
echo "aaa";
}
}
Run Code Online (Sandbox Code Playgroud)
服务提供者代码
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class TestServiceProvider extends ServiceProvider
{
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register services.
*
* @return void
*/
public function register()
{
//
$this->app->bind('App\Service\Tests', function($app){
return new \App\Service\Tests();
});
}
}
Run Code Online (Sandbox Code Playgroud)
然后我将这个提供者添加到config/app,php->providers
然后我创建了一个控制器
namespace App\Http\Controllers\test;
use App\Http\Controllers\Controller;
use App\Service\Tests as tests;
class Test extends Controller
{
public function index()
{
$t = new tests();
$t -> test();
}
}
Run Code Online (Sandbox Code Playgroud)
所以,我可以Tests像这样使用我的,为什么我需要像官方网站一样通过依赖注入来使用它:
public function index(tests $test)
{
$test->test();
}
Run Code Online (Sandbox Code Playgroud)
我看到了一些关于 DI 和 IoC 的文档或文章,但是,我只是不明白它的用途和好处是什么
Hie*_* Le 14
首先,Laravel 使用服务容器和服务提供者,而不是服务器容器或服务器提供者:)
以下是使用依赖项注入 (DI) 的一些好处:
因为您的Test类构造函数非常简单,所以您看不到依赖项注入的好处。想想这样的类:
class Complex {
public function __construct(
FooService $fooService,
BarService $barService,
int $configValue
) {
}
}
Run Code Online (Sandbox Code Playgroud)
如果没有 DI,您必须获取(或创建)$fooServiceand 的实例,每次需要该类的新实例时$barService,$configValue从配置文件中检索 的值。Complex
使用DI,您告诉服务容器如何创建Complex实例一次,然后容器可以通过一次调用为您提供正确的实例(例如$container->make(Complex::class))
继续前面的例子。如果FooService和 也BarService依赖于其他类会发生什么?
如果没有 DI,您必须创建依赖对象的实例(并希望它们不依赖于其他类)。这通常以创建一个类的多个实例结束,浪费代码和计算机内存。
使用 DI,所有依赖对象都由容器创建(您必须先向容器注册这些类)。如果需要,容器还设法只保留每个类的一个实例,这样可以节省代码量以及程序使用的内存量。
singleton要在当前请求的整个生命周期中只保留类的一个实例,您可以使用singletonmethod 而不是bind
laravel 的服务提供者
服务提供者是所有 Laravel 应用程序引导的中心位置。您自己的应用程序以及 Laravel 的所有核心服务都是通过服务提供者引导的。
但是,我们所说的“自举”是什么意思?一般来说,我们指的是注册事物,包括注册服务容器绑定、事件监听器、中间件,甚至路由。服务提供商是配置应用程序的中心位置。
如果您打开 Laravel 附带的 config/app.php 文件,您将看到一个 providers 数组。这些是将为您的应用程序加载的所有服务提供者类。当然,其中许多是“延迟”提供者,这意味着它们不会在每次请求时加载,而只会在实际需要它们提供的服务时加载。
想象一下,您创建了一个需要多个依赖项的类,一般来说,您可以这样使用它:
$foo = new Foo(new Bar(config('some_secret_key')), new Baz(new Moo(), new
Boo()), new Woo('yolo', 5));
Run Code Online (Sandbox Code Playgroud)
这是可行的,但您不想在每次尝试实例化此类时都弄清楚这些依赖项。这就是为什么您要使用服务提供者的原因,其中您可以将此类的 register 方法定义为:
$this->app->singleton('My\Awesome\Foo', function ($app) {
return new Foo(new Bar(config('some_secret_key')), new Baz(new Moo(), new
Boo()), new Woo('yolo', 5));
});
Run Code Online (Sandbox Code Playgroud)
这样,如果你需要使用这个类,你可以在控制器中输入提示(容器会弄清楚)或手动请求它,如
$foo = app(My\Awesome\Foo::class). Isn't that easier to use? ;)
Run Code Online (Sandbox Code Playgroud)
下面的链接将指导您如何编写自己的服务提供者并注册它们并与您的 Laravel 应用程序一起使用。
https://laravel.com/docs/5.7/providers
| 归档时间: |
|
| 查看次数: |
12825 次 |
| 最近记录: |