/**
* 設(shè)置$request數(shù)據(jù),自動覆蓋更新
* @param array $data
*/
function set( array $data )
{
$key = key($data);// 獲取數(shù)組的鍵名
$rawData = $this->$key ?: [];// 獲取原數(shù)據(jù)
$data = array_merge($rawData, $data[$key]);// 合并新數(shù)據(jù)
$this->$key = $data; // 設(shè)置新數(shù)據(jù)
}
在需要設(shè)置更新數(shù)據(jù)的地方直接 $request->set($data);即可
這樣做的好處是可以更新已有的值
建議寫一下怎么調(diào)用,不然還得研究一下
<?php
namespace app\middleware;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
/**
* 處理請求數(shù)據(jù)
*/
class Prdata implements MiddlewareInterface
{
public function process(Request $request, callable $handler): Response
{
$getData = $request->get();
// 處理get數(shù)據(jù)
if (!empty($getData)) {
foreach ($getData as $key => $value) {
is_string($value) && $getData[$key] = trim($value);
}
// 設(shè)置get數(shù)據(jù)
request()->set([
'_data' => [
'get' => $getData
]
]);
}
// 請求繼續(xù)向洋蔥芯穿越
$response = $handler($request);
return $response;
}
}
上面方法 有問題 舊的請求數(shù)據(jù)都沒了
以下方法不會銷毀舊的數(shù)據(jù)
/**
* 設(shè)置$request數(shù)據(jù),自動覆蓋更新
* @param string $method
* @param array $data
*/
function set(string $method, array $data)
{
$method = strtolower($method);
$newData = $this->_data; // 復(fù)制原始數(shù)據(jù)
$newMethodData = array_merge($newData[$method] ?? [], $data); // 合并特定方法的數(shù)據(jù)
$this->_data[$method] = $newMethodData; // 更新對象數(shù)據(jù)
}
非常感謝,正好需要~