實現(xiàn)自定義 Response 類。以修改響應頭 Server 字段默認為 nginx 來舉例。
想設置 http 響應頭 Server 字段默認值為 nginx,故我作了以下修改:
<?php
//省略版權信息,見諒。
namespace support;
/**
* Class Response
* @package support
*/
class Response extends \Webman\Http\Response
{
public function __construct(
$status = 200,
$headers = array(),
$body = ''
) {
$this->_status = $status;
$this->_header = $headers;
$this->_body = $body;
//偽裝 nginx 服務器
if(!isset($this->_header['Server'])){
$this->_header['Server'] = 'nginx';
}
}
}
<?php
//省略版權信息,見諒
namespace Webman\Exception;
use Throwable;
use Webman\Http\Request;
// use Webman\Http\Response;
use support\Response;
interface ExceptionHandlerInterface
{
//省略代碼...
}
<?php
//省略版權信息,見諒
namespace Webman\Exception;
use Throwable;
use Psr\Log\LoggerInterface;
use Webman\Http\Request;
// use Webman\Http\Response;
use support\Response;
/**
* Class Handler
* @package support\exception
*/
class ExceptionHandler implements ExceptionHandlerInterface
{
//省略代碼...
}
<?php
//省略版權信息,見諒
namespace Webman;
use Webman\Http\Request;
// use Webman\Http\Response;
use support\Response;
interface MiddlewareInterface
{
//省略代碼...
}
<?php
//省略版權信息,見諒
namespace Webman;
use Workerman\Worker;
use Workerman\Timer;
use Workerman\Connection\TcpConnection;
use Webman\Http\Request;
// use Webman\Http\Response;
use support\Response;
use Webman\Route\Route as RouteObject;
use Webman\Exception\ExceptionHandlerInterface;
use Webman\Exception\ExceptionHandler;
use Webman\Config;
use FastRoute\Dispatcher;
use Psr\Container\ContainerInterface;
use Monolog\Logger;
/**
* Class App
* @package Webman
*/
class App
{
//省略代碼...
}
以上改法測試可用,但顯然不是“正?!弊龇?/strong>
雖然以上能達到效果,但是不可能期望每次 composer install 之后都要改 vendor 內的源碼。
我該如何正常實現(xiàn)自定義 Response 類?
直接改support/Response.php就行了
只修改 support/Response.php 能夠覆蓋絕大多數(shù)的情況。
但存在以下情況,返回的是 Webman\Http\Response 類:
1,修改start.php use support\App;
2, class App extends \Webman\App
然后
protected static function send(TcpConnection $connection, $response, Request $request)
{
if ($response instanceof \Workerman\Protocols\Http\Response) {
$response->header('Server', 'Tomcat');
}
parent::send($connection, $response, $request);
}
可以這樣實現(xiàn)
#File: support/middleware/StaticFile.php
//添加
$response->withHeader('Server', 'nginx');
#File: support/Response.php
//添加
public function __construct(
$status = 200,
$headers = array(),
$body = ''
) {
$this->_status = $status;
$this->_header = $headers;
$this->_body = $body;
if (!isset($this->_header['Server'])) {
$this->_header['Server'] = 'nginx';
}
}
#File: config/route.php
//添加
Route::any(
'/{notfound:.*}',
function ($request) {
//自己實現(xiàn)404響應
//URL根路徑適當自己處理一下
return json(['status' => 404])->withStatus(404);
}
);