Request Extension 请求的扩展

Because it is such a foundational piece of the framework and is instantiated very early in the request cycle, extending the Request class works a little differently than the previous examples.

由于这玩意儿是框架里面非常基础的部分,并且在请求流程中很早就被实例化,所以要扩展 Request 类的方法与之前相比是有些许不同的。

First, extend the class like normal:

首先还是要写个子类:

namespace QuickBill\Extensions;
class Request extends \Illuminate\Http\Request {
    // Custom, helpful methods here...
}

Once you have extended the class, open the bootstrap/start.php file. This file is one of the very first files to be included on each request to your application. Note that the first action performed is the creation of the Laravel $app instance:

子类写好后,打开 bootstrap/start.php 文件。该文件是应用的请求流程中最早被载入的几个文件之一。要注意被执行的第一个动作是创建 Laravel 的 $app 实例:

$app = new \Illuminate\Foundation\Application;

When a new application instance is created, it will create a new Illuminate\Http\Request instance and bind it to the IoC container using the request key. So, we need a way to specify a custom class that should be used as the "default" request type, right? And, thankfully, the requestClass method on the application instance does just this! So, we can add this line at the very top of our bootstrap/start.php file:

当新的应用实例创建后,它将会创建一个 Illuminate\Http\Request 的实例并且将其绑定到 IoC 容器里,键名为 request。所以我们需要找个方法来将一个自定义的类指定为“默认的”请求类,对不对?而且幸运的是,应用实例有一个名为 requestClass 的方法就是用来干这事儿的!所以我们只需要在 bootstrap/start.php 文件最上面加一行:

use Illuminate\Foundation\Application;
Application::requestClass('QuickBill\Extensions\Request');

Once you have specified the custom request class, Laravel will use this class anytime it creates a Request instance, conveniently allowing you to always have an instance of your custom request class available, even in unit test!

一旦你指定了自定义的请求类,Laravel 将在任何时候都可以使用这个 Request 类的实例。并使你很方便的能随时访问到它,甚至单元测试也不例外!

results matching ""

    No results matching ""