我刚刚安装了Codeignit4.1.1,安装过程顺利进行,没有任何警告,但是我的VSCode没有检测到一些函数,它们是getGet()、getPost()、getVar()和所有其他incomingRequest函数。尽管该函数在4.0.x版本中运行良好,但为什么它不能用于4.1.x?
顺便说一句,即使在上面的函数中有一个警告,程序仍然可以运行,但是这个警告是恼人的。
截图:我的VSCode:https://prnt.sc/z2pevk
发布于 2021-07-30 10:05:06
虽然接受的答案运行良好,但编辑vendor文件并不是一个好做法,因为下次运行composer update或composer install时,所有这些更改都将被撤消。
因此,不应该碰vendor文件夹。
回到问题的上下文中,这个错误背后的原因是RequestInterface只强制执行由类实现的以下方法:
getIPAddress(): stringisValidIP(string $ip, string $which = null): boolgetMethod(bool $upper = false): stringgetServer($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链接上查阅)
我希望我已经给出了一个很好和详细的解释。
发布于 2021-02-12 21:38:37
在屏幕截图中,您将检查显式声明为$request的RequestInterface方法,并且这个接口只有IntelliSense中显示的四个方法。它之所以有效,是因为实现该接口的类具有您要寻找的方法。
我这里没有VS代码,但是我认为如果尝试$this->request,您会发现您正在寻找什么,因为除了引用同一个对象之外,它没有显式声明的类型。
您希望看到的方法来自IncomingRequest,它扩展了Request和Request,实现了RequestInterface。
发布于 2021-08-23 16:18:16
只是从BaseController扩展,而不是通过Controller。
https://stackoverflow.com/questions/66152027
复制相似问题