扩展CodeIgniter中的Controller类

Yek*_*ver 19 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
Run Code Online (Sandbox Code Playgroud)

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

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

Roo*_*eyl 27

我认为你把你的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 */
Run Code Online (Sandbox Code Playgroud)

在/ application/controllers中

class foo extends MY_Controller {
    public function __construct() {
       parent::__construct();
    }
...
}
Run Code Online (Sandbox Code Playgroud)

要么

class bar extends another_controller {
    public function __construct() {
       parent::__construct();
    }
...
}
Run Code Online (Sandbox Code Playgroud)

  • 当然,共享方法可以保护而不是公开.因此它们不会被路由,但扩展控制器可以访问它们. (6认同)

Adm*_*ama 5

我在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
}
Run Code Online (Sandbox Code Playgroud)

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


小智 5

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

require_once(APPPATH."controllers/MyParentController.php");
class MyChildController extends MyParentController {
...
Run Code Online (Sandbox Code Playgroud)