如何从中间件向 Laravel 的 IOC 容器添加对象

How to Add an Object to Laravel's IOC Container from Middleware

我想在我的中间件中创建一个对象(在本例中,是来自 Eloquent 查询的集合),然后将它添加到 IOC 容器中,这样我就可以在我的控制器中输入提示方法签名访问它。

这可能吗?我在网上找不到任何例子。

您可以通过几个步骤轻松做到这一点。

创建新的中间件(随意命名)

php artisan make:middleware UserCollectionMiddleware

创建将扩展 Eloquent 数据库集合的新集合 class。此步骤不是必需的,但可以让您将来使用不同的集合类型创建不同的绑定。否则你只能对 Illuminate\Database\Eloquent\Collection.

进行一次绑定

app/Collection/UserCollection.php

<?php namespace App\Collection;

use Illuminate\Database\Eloquent\Collection;

class UserCollection extends Collection {

}

中添加您的绑定app/Http/Middleware/UserCollectionMiddleware.php

<?php namespace App\Http\Middleware;

use Closure;
use App\User;
use App\Collection\UserCollection;

class UserCollectionMiddleware {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        app()->bind('App\Collection\UserCollection', function() {
            // Our controllers will expect instance of UserCollection
            // so just retrieve the records from database and pass them
            // to new UserCollection object, which simply extends the Collection
            return new UserCollection(User::all()->toArray());
        });

        return $next($request);
    }

}

不要忘记将中间件放在所需的路由上,否则会报错

Route::get('home', [
    'middleware' => 'App\Http\Middleware\UserCollectionMiddleware',
    'uses' => 'HomeController@index'
]);

现在您可以像这样在您的控制器中键入提示此依赖关系

<?php namespace App\Http\Controllers;

use App\Collection\UserCollection;

class HomeController extends Controller {

    /**
     * Show the application dashboard to the user.
     *
     * @return Response
     */
    public function index(UserCollection $users)
    {
        return view('home', compact('users'));
    }

}