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

voi*_*ate 4 php ioc-container laravel laravel-5

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

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

sha*_*ddy 5

你可以很容易地做到这一点,只需几个步骤。

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

php artisan make:middleware UserCollectionMiddleware
Run Code Online (Sandbox Code Playgroud)

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

应用程序/集合/UserCollection.php

<?php namespace App\Collection;

use Illuminate\Database\Eloquent\Collection;

class UserCollection extends Collection {

}
Run Code Online (Sandbox Code Playgroud)

添加您的绑定 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);
    }

}
Run Code Online (Sandbox Code Playgroud)

不要忘记把中间件放在想要的路由上,否则会报错

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

现在您可以像这样在控制器中输入提示此依赖项

<?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'));
    }

}
Run Code Online (Sandbox Code Playgroud)