在CodeIgniter中扩展Controller类

332nm8kg  于 8个月前  发布在  其他
关注(0)|答案(5)|浏览(77)

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

Fatal error: Class 'Profile' not found

CodeIgniter试图在我正在运行的index.php中找到这个类。
我的错在哪里?或者也许有更好的方法来标记出共同的逻辑?

yhived7q

yhived7q1#

我认为你已经把你的MY_Controller放在/application/core中,并在配置中设置了前缀。但是,我会小心使用index作为类名。作为Codeigniter中的一个函数/方法,它有一个专用的行为。
如果你想扩展这个控制器,你需要把这些类放在同一个文件中。
例如,In /应用程序核心

/* 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 */

In /application/controllers

class foo extends MY_Controller {
    public function __construct() {
       parent::__construct();
    }
...
}

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

i2loujxw2#

不需要将父类复制/粘贴到所有控制器类中的解决方案:
1.将父类放在core文件夹中。
1.在包含父类的所有类的开头放置一个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
}
vptzau2j

vptzau2j3#

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

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

pokxtpni4#

你扩展的所有类都应该位于application/CORE目录中,所以在你的例子中,My_Controller和Profile都应该位于那里。所有“端点”控制器将位于application/controllers文件夹中

更新

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

gc0ot86w

gc0ot86w5#

经过一些斗争与版本3和这个问题,我决定这是一个不坏的解决方案.

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

在system/core/CodeIgniter.php中第一行的位置添加第二行

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

相关问题