【发布时间】:2021-10-20 17:49:59
【问题描述】:
在 Codeignter 4 中,我们不能在 BaseController 中使用构造函数。但是方法 initController() 会做到这一点。但是如何从派生控制器的构造函数中调用这个方法呢?
我的问题是BaseController::is_allowed() 方法将完成所有对所有派生控制器类通常有用的基本功能。但是要工作 BaseController::is_allowed() , BaseController::__construct() 应该在此之前执行。但与 CI-4 中一样,BaseController 中不允许使用构造函数。它可以有BaseController::initController()。但是问题是这个方法只有在DerivedClass::__construct()之后才会执行。
我需要在执行每个派生类方法之前执行BaseController::is_allowed()。所以我在派生控制器的构造函数中调用BaseController::is_allowed() 方法。但是派生类构造函数在BaseController::initController() 执行之前执行。所以BaseController::is_allowed() 不起作用。
BaseController.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
class BaseController extends Controller
{
public $request;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
// Doing all basic setups here that are needed to all other methods in this class.
// This method will be called only after derivedClass::__construct().
// But CI-4 not allows to use __construct() method in BaseController class.
// This causes my problem.
}
function is_allowed()
{
// Provides all basic features for all derived controller classes.
// But to work code in this method, initController() method should execute first.
}
}
而派生类为
Users.php
<?php
namespace App\Controllers;
class Users extends BaseController
{
public function __construct()
{
// BaseController::is_allowed() will provide all basic features for this controller.
// To work this method, BaseController::initController() should execute.
// But this will execute only after this ( __construct()) constuctor.
// In Codeignier-3, BaseController::__construct() was possible.
// It will execute before derived class constructor.
$this->is_allowed();
}
}
【问题讨论】:
-
您是否尝试将
RequestInterface $request, ResponseInterface $response, LoggerInterface $logger添加到构造参数中? -
不,我需要得到这个东西。我如何获得这些变量,因为它在父控制器中可用,但在其构造函数中不可用。派生类::__construct()方法会在执行parent::initController()之前执行
-
codeigniter4.github.io/userguide/incoming/… 应用程序的主请求实例始终可用作类属性
$this->request。来自官方文档
标签: php codeigniter-4