業(yè)務(wù)需要, 將傳過(guò)來(lái)的用戶(hù)名, 加一個(gè)前綴保存, 但是頻繁訪問(wèn)的話(huà), 這個(gè)前綴會(huì)一直加.
比如傳的 username 是 test 前綴是 default_, 如果頻繁訪問(wèn), 這個(gè) username 會(huì)變成 default_default_test 前綴會(huì)一直往前面加...是我寫(xiě)法有問(wèn)題, 還是用的不對(duì)?
這是運(yùn)行環(huán)境
-------------------------------------------- WORKERMAN ---------------------------------------------
Workerman/5.1.0 PHP/8.4.4 (Jit off) Darwin/23.6.0
$payload = $request->get();
$prefix = 'default_';
foreach ($payload as $key => $value) {
if ('username' == $key) {
$payload[$key] = $prefix . $value;
}
}
$request->setGet($payload);
補(bǔ)充一下: 上面的修改代碼是在中間件里寫(xiě)的, 使用這個(gè)參數(shù)的時(shí)候是在控制器里.
if ('username' == $key) {
// 如果值不以 $prefix 開(kāi)頭,才添加前綴
if (strpos($value, $prefix) !== 0) {
$payload[$key] = $prefix . $value;
}
}
復(fù)用 Request
對(duì)象時(shí)沒(méi)有清理臟數(shù)據(jù)。
<?php
/**
* This file is part of webman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.wtbis.cn/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace support;
/**
* Class Request
*
* @package support
*/
class Request extends \Webman\Http\Request
{
public function clearGetData(): void
{
if (isset($this->data['get'])) {
unset($this->data['get']);
}
}
}
<?php
declare(strict_types=1);
namespace app\middleware;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
class ClearGetData implements MiddlewareInterface
{
public function process(Request $request, callable $handler): Response
{
// TODO: Implement process() method.
$request->clearGetData();
return $handler($request);
}
}
<?php
/**
* This file is part of webman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.wtbis.cn/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
return [
'' => [
\app\middleware\ClearGetData::class,
],
];
<?php
namespace app\middleware;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
class Test implements MiddlewareInterface
{
public function process(Request $request, callable $handler) : Response
{
$payload = $request->get();
$prefix = 'default_';
foreach ($payload as $key => $value) {
if ('username' == $key) {
$payload[$key] = $prefix . $value;
}
}
$request->setGet($payload);
return $handler($request);
}
}
<?php
return [
'' => [
\app\middleware\Test::class
]
];
<?php
namespace app\controller;
use support\Request;
class IndexController
{
public function index(Request $request)
{
return json($request->get());
}
}
刷新了N次也沒(méi)復(fù)現(xiàn)