扩展CodeIgniter中的Controller类

时间:2011-12-01 13:36:32

标签: php codeigniter codeigniter-2

我有class MY_Controller extends CI_Controller和大型配置文件部分的通用逻辑,因此I'va尝试使用配置文件部分的通用逻辑创建class Profile extends MY_Controller,并且与此部分相关的所有类都应该扩展此Profile类,因为我理解正确,但当我尝试创建class Index extends Profile时,我收到了一个错误:

Fatal error: Class 'Profile' not found

CodeIgniter尝试在我正在运行的index.php中找到此类。

我的错误在哪里?或者也许有更好的方法来标出共同的逻辑?

5 个答案:

答案 0 :(得分:27)

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

如果您想扩展该控制器,则需要将这些类放在同一个文件中。

E.g。在/ 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 */

在/ application / controllers

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

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

答案 1 :(得分:4)

我在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
}

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

答案 2 :(得分:1)

使用Codeigniter 3是可能的。仅包含父文件就足够了。

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

答案 3 :(得分:0)

您正在扩展的所有类都应该位于application / CORE目录中,因此在您的情况下,My_Controller和Profile都应该存在。所有“终点”控制器都将存在于应用程序/控制器文件夹中

更新

我的立场得到了纠正。扩展类应该存在于同一个文件中。 @ Rooneyl的答案显示了如何实施

答案 4 :(得分:-1)

在与版本3和这个问题进行了一些斗争后,我认为这不是一个糟糕的解决方案......

bar = progressbar.ProgressBar()
for i in range(101):
    sleep(0.01)
    bar.update(i)
    ch = getch.getch()

添加第二行,其中第一行存在于system / core / CodeIgniter.php

[如果还不晚,我建议强烈反对php和/或CodeIgniter。]

相关问题