Day25 跟着官方文件学习Laravel-Service Container

Service Container 是管理类别依赖和执行依赖注入的一个容器。

官方文件告诉我们可以利用Contrustor或setter的方式注入我们需要用的类别。

如下面范例:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
use App\Models\User;

class UserController extends Controller
{
    /**
     * The user repository implementation.
     *
     * @var UserRepository
     */
    protected $users;

    /**
     * Create a new controller instance.
     *
     * @param  UserRepository  $users
     * @return void
     */
    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }

    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        $user = $this->users->find($id);

        return view('user.profile', ['user' => $user]);
    }
}

范例中我们需要产生 UserRepository 来帮我们到资料库中索取我们需要的user资料,但我们这边没有实际把他 new 出来,而是使用依赖注入的方式,而如何 new 就是 Service Container 帮我们处理的事情。

这个地方我们利用实际的类别来撰写,若是利用 interface 的方式要使用依赖注入的话,我们需要去利用 service provider 告诉容器我们呼叫到某个 interface 时请你帮我创建出什麽实例出来。

这时我们需要在容器内先绑定我们预先要使用的类别,我们可以利用 $this->app 呼叫容器,并利用 bind 方法将我们的 interface 跟 类别绑定
如下

<?php

namespace App\Animal;

interface Animal 
{
    public function say();
}
<?php

namespace App\Animal;

class Dog implements Animal
{
    public function say(){
        return "汪汪";
    }
}
use App\Services\Transistor;
use App\Services\PodcastParser;

$this->app->bind(Animal::class, function () {
    return new Dog();
});

若我们需要在不同场景运用不同的类别实作,我们可以利用以下方法来实现

<?php

namespace App\Animal;

class Cat implements Animal
{
    public function say(){
        return "喵喵";
    }
}
$this->app->when(CatController::class)
          ->needs(Animal::class)
          ->give(function () {
              return new Cat();
          });

$this->app->when(DogController::class)
          ->needs(Animal::class)
          ->give(function () {
              return new Dog();
          });

若我们想在程序中调用容器中的物件我们可以用 make

$transistor = $this->app->make(Animal::class);

我们也可以在方法调用时,注入该物件,如同我们在UserController里调用UserService

public function store(Request $request, UserService $userService)
    {
        $account = $request->account;
        $password = $request->password;
        $username = $request->username;
        try{
            if($userService->signUp($account, $password, $username)){
                return response()->json([
                    'success' => 'true'
                ]);
            }
        } catch (PDOException $e){
            return response()->json([
                'success' => 'false',
                'error'=> 'DB error'
            ]);
        }catch (\Exception $e){
            return response()->json([
                'success' => 'false',
                'error'=> $e->getMessage()
            ]);
        }
    }

好~今天了解了Service Container,明天继续了解其他功能。


<<:  DAY 27 如何使用PyImgur

>>:  DAY 27 Big Data 5Vs – Value(价值) – QuickSight(1)

Day_19 : 让 Vite 来开启你的Vue 之 计算属性 Computed

Hi Dai Gei Ho~ 我是Winnie~ 在今天文章中 我们主要会针对 Compositio...

【Day3】前端React +Antd 的环境(Docker化)建立 (上)

1.前端的建立过程(上): 我是在本机电脑运行起来本地版本 Container 的静态前端 Serv...

.Net Core Web Api_笔记09_web api的属性路由模板两种写法_路由模板使用

在.net core mvc跟.net core web api专案中预设各自采用的一些配置 有不太...

Day 06-大 module 小 module,能够重复使用又好维护的就是好 module

大 module 小 module,能够重复使用又好维护的就是好 module 上一章介绍 modu...

Day3 - Yolo? 那是什麽? 能喝吗?

(今日内容将有数学式,请谨慎服用) 今天要介绍的主角,可以说他是影响模型输出结果以及训练过程中最大的...