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

时间:2015-05-29 20:18:45

标签: php laravel laravel-5 ioc-container

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

这可能吗?我无法在网上找到任何示例。

1 个答案:

答案 0 :(得分:4)

您可以通过几个步骤轻松完成这项工作。

创建新的中间件(按照您的意愿命名)

php artisan make:middleware UserCollectionMiddleware

创建将扩展Eloquent数据库集合的新集合类。此步骤不是必需的,但将来可以使用不同的集合类型创建不同的绑定。否则,您只能对Illuminate\Database\Eloquent\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'));
    }

}