【问题标题】:How to Add an Object to Laravel's IOC Container from Middleware如何从中间件向 Laravel 的 IOC 容器添加对象
【发布时间】:2015-08-12 20:08:15
【问题描述】:

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

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

【问题讨论】:

  • 不明白您的问题,但您可以通过这种方式将实例添加到IoC Contaioner,例如:app()->instance('foo', $foo);

标签: php laravel laravel-5 ioc-container


【解决方案1】:

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

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

php artisan make:middleware UserCollectionMiddleware

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多