【发布时间】:2019-03-30 17:47:19
【问题描述】:
我刚刚开始使用 Laravel,我真的很困惑 service contains 和 service providers 我搜索了一些示例,例如以下服务代码:
namespace App\Service;
class Tests
{
public function test()
{
echo "aaa";
}
}
服务提供者的代码
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();
});
}
}
然后我将此提供程序添加到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();
}
}
所以,我可以像这样使用我的Tests,为什么我需要像官方网站一样通过依赖注入来使用它:
public function index(tests $test)
{
$test->test();
}
我看过一些关于 DI 和 IoC 的文档或文章,但是我就是不明白它的用途和好处
【问题讨论】:
-
Laravel 服务容器帮助我们管理依赖关系的 4 种方式 christoph-rumpel.com/2019/08/…