laravel8 IOC容器的基本使用
php
design, php
字数统计: 543(字)
阅读时长: 2(分)
参考文献
laravel服务容器:https://learnku.com/docs/laravel/8.x/container/9361
实现步骤
定义接口类
创建 app/Interfaces 文件夹,创建测试接口类 TestIocInterface.php,并定义接口契约。
1 2 3 4 5 6 7
| <?php namespace App\Interfaces;
interface TestIocInterface { public function test_string(string $string) : string; }
|
1)为了方便管理,定义一个契约目录,专门要来存放接口,将要实现的功能定义成接口,然后子类实现。
2)当然了,不这样使用也可以通过其它方法来实现服务容器与服务提供者的结合使用。
定义服务实现类
创建 app/Services 文件夹,创建测试接口类 TestIocService.php,实现定义的接口契约。
1 2 3 4 5 6 7 8 9 10 11 12
| <?php namespace App\Services;
use App\Interfaces\TestIocInterface;
class TestIocService implements TestIocInterface { public function test_string(string $string): string { return "你的字符串返回结果是 {$string}"; } }
|
创建服务提供者
1
| php artisan make:provider TestIocServiceProvider
|
编辑生成的 TestIocServiceProvider.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| <?php
namespace App\Providers;
use App\Services\TestIocService; use Illuminate\Support\ServiceProvider;
class TestIocServiceProvider extends ServiceProvider {
public function register() { $this->app->bind('App\Interfaces\TestIocInterface', function(){ return new TestIocService(); });
$this->app->singleton('TestIocInterface', function(){ return new TestIocService(); }); }
public function boot() { } }
|
注册服务提供者
这一步需要在app/config/app.php文件中的providers数组中将服务提供者注册到应用中。
1 2 3 4 5
| <?php 'providers' => [ App\Providers\TestIocServiceProvider::class, ],
|
测试
创建测试控制器,并编辑以下文件
1
| php artisan make:controller TestIocController
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| <?php
namespace App\Http\Controllers;
use App\Interfaces\TestIocInterface; use Illuminate\Http\Request; use Illuminate\Support\Facades\App;
class TestIocController extends Controller {
public function test(TestIocInterface $test) { echo $test->test_string("啦啦啦啦啦"); }
public function test2() { $testIoc = App::make('TestIocInterface'); echo $testIoc->test_string("啦啦啦啦啦"); } }
|
编写访问路由
1 2 3 4 5 6
| <?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\TestIocController;
Route::get('testioc', [TestIocController::class, 'test']); Route::get('testioc2', [TestIocController::class, 'test2']);
|