【问题标题】:Codeigniter - extending controller does not workCodeigniter - 扩展控制器不起作用
【发布时间】:2023-03-06 07:23:01
【问题描述】:

我正在尝试使用我自己的类扩展一个控制器,该类扩展了默认的 CI_Controller 类。除非它不起作用。

它说找不到我的子类。我的子类位于 application/core 并命名为 My_Control_Panel。

我的类在我的子类上扩展:

if (!defined('BASEPATH')) exit('No direct script access allowed');

class Developers extends My_Control_Panel
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->database();

        $this->checkIfLoggedIn();
        $this->checkIfAllowedToViewPage();
}

我的子班:

if (!defined('BASEPATH')) exit('No direct script access allowed');

class My_Control_Panel extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }
}

它一直说找不到我的子类,但它应该可以工作。

【问题讨论】:

    标签: php codeigniter extending


    【解决方案1】:

    您应该在您的core 文件夹中将您的文件命名为My_Controller.php 然后你输入你的代码像

    if (!defined('BASEPATH')) exit('No direct script access allowed');
    
    class My_Control_Panel extends CI_Controller
    {
        public function __construct()
        {
            parent::__construct();
        }
    }
    

    这是在 CodeIgniter 中执行此操作的正确方法,而不是在第一个答案中提到的包含一个 ..

    【讨论】:

    • 是的,但我们在这里谈论的是application/core,而不是system/core ..check the manual
    • 我可以将 My_Controller.php 文件重命名为 My_Form.php 之类的文件吗?
    • 不,你不能,因为这与你的控制器有关,但如果你想扩展 CI_Form,那么是的,你可以称之为 My_Form
    【解决方案2】:

    如果您希望 CI 接听您的扩展课程,您必须将其命名为 MY_ControllerMY_ 部分是可配置的,但其他部分不是。

    MY_ 部分来自 config/config.php:

    $config['subclass_prefix'] = 'MY_';
    

    【讨论】:

    • 是的,我尝试更改它和其他东西,但它无论如何都找不到我的子类
    • 这通常以小写/大写问题告终,您的示例有My 和小写y。也许这就是原因。 (或者可能是你的配置有My_
    • 抱歉,是复制错误。 :) 在我的代码中是 MY_
    【解决方案3】:

    您需要在子类 (Developers) 中包含父类 (My_Control_Panel),如下所示:

    if (!defined('BASEPATH')) exit('No direct script access allowed');
    
    include_once '../path/to/mycontrolpanel.php';
    
    class Developers extends My_Control_Panel
    {
        // whatever
    }
    

    【讨论】:

    • 但这一点在 CodeIgniter 的用户指南中没有提到。你确定这是正确的方法吗?
    • 它对我有用,但我仍然怀疑这是最好的方法。无论如何感谢。 :)
    猜你喜欢
    • 2017-09-19
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 2017-09-13
    相关资源
    最近更新 更多