虽然接受的答案可以正常工作,但编辑 vendor 文件并不是一个好习惯,因为下次运行 composer update 或 composer install 时,所有这些更改都将被撤消。
因此,vendor 文件夹不应被触及。
回到问题的上下文,这个错误背后的原因是RequestInterface 只强制类实现以下方法:
getIPAddress(): string
isValidIP(string $ip, string $which = null): bool
getMethod(bool $upper = false): string
getServer($index = null, $filter = null)
CodeIgniter Controllers 文件夹通常包含一个 BaseController 类,所有其他控制器都从该类继承,因此您可以简单地在其中重新定义 $request 数据成员,如下所示:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\IncomingRequest; // ADD THIS LINE
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers:
* class Home extends BaseController
*
* For security be sure to declare any new methods as protected or private.
*/
class BaseController extends Controller
{
/**
* Instance of the main Request object.
*
* @var IncomingRequest
*/
protected $request; // NOTICE THIS LINE AND THE COMMENT ABOVE IT
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* @var array
*/
protected $helpers = [];
/**
* Constructor.
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @param LoggerInterface $logger
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
//--------------------------------------------------------------------
// Preload any models, libraries, etc, here.
//--------------------------------------------------------------------
// E.g.: $this->session = \Config\Services::session();
}
}
我们所做的只是将类型从RequestInterface 切换到IncomingRequest,其中包含RequestInterface 中定义的方法的实现以及该类定义的其他方法。
请注意,$request 数据成员的访问修饰符必须是 protected,因为其他控制器将继承此控制器。
对于 CodeIgniter v4.1.2,该问题已由框架通过应用与上述解决方案类似的解决方案来解决((更多详细信息,请访问Github diff link))
我希望我已经给出了一个好的和详细的解释。