Webman 1.5 能在中間件中能修改 Request 嗎?
在文檔中介紹了修改 Response 的例子,如果我想修改請(qǐng)求過(guò)來(lái)的 post 的數(shù)據(jù),該怎么操作?
<?php
namespace app\middleware;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
class AccessControlTest implements MiddlewareInterface
{
public function process(Request $request, callable $handler) : Response
{
// 如果是options請(qǐng)求則返回一個(gè)空響應(yīng),否則繼續(xù)向洋蔥芯穿越,并得到一個(gè)響應(yīng)
$response = $request->method() == 'OPTIONS' ? response('') : $handler($request);
// 給響應(yīng)添加跨域相關(guān)的http頭
$response->withHeaders([
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Allow-Origin' => $request->header('origin', '*'),
'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'),
]);
return $response;
}
}
任何PHP框架都遵循的基本規(guī)則,比如繼承、對(duì)象的引用傳遞。
您可以 在自定義請(qǐng)求類里面實(shí)現(xiàn)你的功能 support/Request.php
反射,大概就這樣,可能有 bug,但原理就是這個(gè)原理。
public function process(Request $request, callable $next): Response
{
$refObj = new \ReflectionClass(Request::class);
$buffer = $refObj->getProperty('buffer');
$buffer->setAccessible(true);
$wholeRequest = $buffer->getValue($request);
[$headers, $body] = explode("\r\n\r\n", $wholeRequest);
$body = 'hello=world';
$buffer->setValue($request, implode("\r\n\r\n", [
$headers,
$body,
]));
$data = $refObj->getProperty('data');
$data->setAccessible(true);
$wholeData = $data->getValue($request);
$wholeData['query_string'] = 'name=yyy';
$wholeData['get'] = ['name' => 'yyy'];
$wholeData['path'] = '/x/y/z';
$data->setValue($request, $wholeData);
$response = $next($request);
return $response;
}
效果如下:
或者像樓上說(shuō)的直接改support/Request
,簡(jiǎn)單得多,如下,不過(guò)不確定改support
目錄是不是一件好事,起碼某些屬性是不能修改的,要注意點(diǎn)。
namespace support;
/**
* Class Request
* @package support
*/
class Request extends \Webman\Http\Request
{
public function __construct(string $buffer)
{
parent::__construct($buffer);
$this->data['query_string'] = 'hello=world';
$this->data['get'] = ['hello' => 'world'];
$this->data['post'] = 'foo=bar';
}
}
```php
/**
*/
function setParams(string $method, array $data)
{
$method = strtolower($method);
if (!isset($this->data[$method])) {
if ($method == 'post'){
$this->parsePost();
}
if ($method == 'get'){
$this->parseGet();
}
}
$rawData = $this->data ?: [];// 獲取原數(shù)據(jù)
$newData = $rawData; // 復(fù)制原始數(shù)據(jù)
$newData[$method] = array_merge($newData[$method] ?? [], $data); // 合并特定方法的數(shù)據(jù)
$this->data = $newData; // 更新對(duì)象數(shù)據(jù)
}