codeigniter:扩展通用控制器 [英] codeigniter: extending common controller

查看:33
本文介绍了codeigniter:扩展通用控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了所有关于此问题的帖子,但没有任何效果.我在带有 Apache2.2 和 PHP5.3.2 的 LAMP 中使用 Codeigniter 2.02

I've read all the post I found regarding this issue but nothing works. I'm using Codeigniter 2.02 in a LAMP with Apache2.2 and PHP5.3.2

我正在尝试创建一个通用控制器,我的通用控制器将从该控制器继承,以便我可以在那里执行常见任务.

I'm trying to create a common controller from which my common controllers will inherit so I can do common tasks there.

我有这个:

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

class Parent_controller extends CI_Controller {

    public function Parent_controller()
    {
        parent::__construct();
    }

    public function index() {
        echo "Hi!";
    }
}

文件:welcome.php

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

class Welcome extends Parent_controller {

    public function __construct()
    {
        parent::__construct();
    }
}

我已经尝试了我找到的下一个解决方案,但都没有奏效:

I've tried the next solutions I've found, but none of them are working:

  • 公共函数__contstruct() 代替公共函数Parent_controller()

  • public function __contstruct() instead of public function Parent_controller()

parent::Parent_controller();

parent::Parent_controller();

将 parent_controller.php 文件放入 core

put the parent_controller.php file into core

将parent_controller.php文件放入controllers

put the parent_controller.php file into controllers

将其添加到 config/config.php:

adding this to config/config.php:

function __autoload($class){
        if (file_exists(APPPATH."(controllers|core)/".$class.EXT)){
             require_once(APPPATH.'(controllers|core)/'.$class.EXT);
       }
}

谢谢大家.

推荐答案

看看 Phil Sturgeon 的这篇文章:

Take a look at this post from Phil Sturgeon:

http://philsturgeon.co.uk/blog/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY

关键是使用本机自动加载,如他的帖子所述:

The key is using the native autoload as explained in his post:

/*
| -------------------------------------------------------------------
|  Native Auto-load
| -------------------------------------------------------------------
| 
| Nothing to do with cnfig/autoload.php, this allows PHP autoload to work
| for base controllers and some third-party libraries.
|
*/
function __autoload($class)
{
    if(strpos($class, 'CI_') !== 0)
    {
        @include_once( APPPATH . 'core/'. $class . EXT );
    }
}

注意

请注意,您需要将所有基本"控制器放在 CI2+ 的 core 文件夹中

As a note, you'll want to put all of your "base" controllers in the core folder for CI2+

这篇关于codeigniter:扩展通用控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆