0

例如,我想向 Request 类添加其他方法,例如getRequiered*($name)在请求中丢失参数的情况下会抛出异常。我想像这样实现它:

class MySmartRequest extends Request {
    // ...
    function getIntRequired($name) {
        $res = $this->get($name, null);
        if (null === $res) { throw new Exception('Missed required param'); }
        return (int) $res;
    }
}

// ...

$app->before(function(Request $r) {
    return new MySmartRequest($r);
});

有可能吗?

4

1 回答 1

1

是的,这是可能的(实际上从未这样做过,以下只是阅读代码的提示)。

您需要创建 的子类Silex\Application,并将run()函数覆盖为如下内容:

public function run(Request $request = null)
{
    if (null === $request) {
        $request = MySmartRequest::createFromGlobals();
    }

    $response = $this->handle($request);
    $response->send();
    $this->terminate($request, $response);
}

为避免重复,您可以尝试以下操作:

public function run(Request $request = null)
{
    if (null === $request) {
        $request = MySmartRequest::createFromGlobals();
    }

    parent::run($request); 
}
于 2014-04-04T12:17:03.523 回答