类型提示 – 永夜 https://www.shuijingwanwq.com 没有不值得去解决的问题,也没有不值得去学习的技术! Thu, 19 May 2022 01:07:59 +0000 zh-Hans hourly 1 https://wordpress.org/?v=7.0 在 Laravel 6 的中间件中注入依赖项的实现 https://www.shuijingwanwq.com/2022/05/19/6433/ https://www.shuijingwanwq.com/2022/05/19/6433/#respond Thu, 19 May 2022 01:07:59 +0000 https://www.shuijingwanwq.com/?p=6433 浏览量: 78 1、查看现有的代码,基于函数 app 实现。app 函数返回 服务容器 实例。无法通过点击 getByName() 跳转至对应的方法。如图1
查看现有的代码,基于函数 app 实现。app 函数返回 服务容器 实例。无法通过点击 getByName() 跳转至对应的方法

图1

<pre class="wp-block-syntaxhighlighter-code">

<?php

namespace App\Http\Middleware;

use App\Services\ThemeService;
use Carbon\Carbon;
use Closure;
use Illuminate\Support\Facades\Route;

class CurrentTheme
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $service = app(ThemeService::class);

		// ...

		$theme = $service->getByName($decrypt['name']);

        // ...

        return $next($request);
    }
}


</pre>
2、参考服务容器的自动注入。可以简单地使用「类型提示」 的方式在类的构造函数中注入那些需要容器解析的依赖项,包括 控制器,事件监听器,队列任务,中间件,等 。实际上,这才是大多数对象应该被容器解析的方式。 3、参考网址:https://stackoverflow.com/questions/35439234/laravel-dependency-injection-in-middleware 4、基于构造函数实现。已可通过点击 getByName() 跳转至对应的方法。如图2
基于构造函数实现。已可通过点击 getByName() 跳转至对应的方法

图2



    protected $themeService;

    public function __construct(ThemeService $themeService)
    {
        $this->themeService = $themeService;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $theme = $this->themeService->getByName('vogue');
	}


 ]]>
https://www.shuijingwanwq.com/2022/05/19/6433/feed/ 0