在CodeIgniter中扩展控制器类


Extending The Controller Class in CodeIgniter

我有class MY_Controller extends CI_Controller和大配置文件部分的共同逻辑,所以我试图为配置文件部分创建class Profile extends MY_Controller,所有与此部分相关的类都应该扩展此配置文件类,因为我理解正确,但是当我试图创建class Index extends Profile时,我收到一个错误:

Fatal error: Class 'Profile' not found

CodeIgniter试图在我正在运行的index.php中找到这个类。

我错在哪里?或者可能有另一种更好的方法来标记公共逻辑?

我认为你已经把你的MY_Controller放在/application/core中,并在配置中设置前缀。不过,我会小心使用index作为类名。作为Codeigniter中的一个函数/方法,它有一个专用的行为。

如果你想扩展这个控制器,你需要把这些类放在同一个文件中。

。In/application core

/* start of php file */
class MY_Controller extends CI_Controller {
    public function __construct() {
       parent::__construct();
    }
...
}
class another_controller extends MY_Controller {
    public function __construct() {
       parent::__construct();
    }
...
}
/* end of php file */

/应用程序/控制器
class foo extends MY_Controller {
    public function __construct() {
       parent::__construct();
    }
...
}

class bar extends another_controller {
    public function __construct() {
       parent::__construct();
    }
...
}

我在Google上找到了这个页面,因为我有同样的问题。我不喜欢这里列出的答案,所以我创造了我自己的解决方案。

1)把你的父类放在core文件夹中。

2)在包含父类的所有类的开头放置一个include语句。

一个典型的控制器可能是这样的:

<?php
require_once APPPATH . 'core/Your_Base_Class.php';
// must use require_once instead of include or you will get an error when loading 404 pages
class NormalController extends Your_Base_Class
{
    public function __construct()
    {
        parent::__construct();
        // authentication/permissions code, or whatever you want to put here
    }
    // your methods go here
}

我喜欢这个解决方案的原因是,创建父类的全部要点是减少代码重复。所以我不喜欢另一个答案建议将父类复制/粘贴到所有控制器类中

这在Codeigniter 3中是可能的。只要包含父文件就足够了。

require_once(APPPATH."controllers/MyParentController.php");
class MyChildController extends MyParentController {
...

你扩展的所有类都应该存在于application/CORE目录中,所以在你的情况下,My_Controller和Profile都应该存在于那里。所有"端点"控制器都位于application/controllers文件夹

我承认错误。扩展类应该位于同一个文件中。@Rooneyl的答案展示了如何实现

经过与版本3和这个问题的一些斗争,我认为这是一个不错的解决方案…

require_once BASEPATH.'core/Controller.php';
require_once APPPATH.'core/MYCI_Controller.php';

在system/core/CodeIgniter.php

中第一行存在的地方添加第二行

[如果还不算太晚,我强烈建议不要使用php和/或CodeIgniter]