Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

php - Codeigniter extending extended MY_Controller

I have strictly followed the how-to article by Phil Sturgeon, to extend the base controller. But I get still some errors.

My 3 classes:

// application/libraries/MY_Controller.php
class MY_Controller extends Controller{
    public function __construct(){
        parent::__construct();
    }
}

// application/libraries/Public_Controller.php
class Public_Controller extends MY_Controller{
    public function __construct(){
        parent::__construct();

    }    
}

// application/controllers/user.php
class User extends Public_Controller{
    public function __construct(){
        parent::__construct();
    }
}

Fatal error: Class 'Public_Controller' not found in /srv/www/xxx/application/controllers/user.php on line 2

Curious is that the following snippet is working, if I directly extends from MY_Controller:

// application/controllers/user.php
class User extends MY_Controller{
    public function __construct(){
        parent::__construct();
    }
}

I have loaded the controllers via __autoload() or manually. The controllers are loaded succesfully.

CI-Version: 1.7.3

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to require the Public Controller in your MY_Controller

// application/libraries/MY_Controller.php
class MY_Controller extends Controller{
    public function __construct(){
        parent::__construct();
    }
}

require(APPPATH.'libraries/Public_Controller.php');

You get the error because Public_Controller was never loaded. Doing this would allow you to extend from Public_Controller

I like what you are doing because I do that all the time.

You can do this also in your MY_Controller when you want to create an Admin_Controller

// application/libraries/MY_Controller.php
class MY_Controller extends Controller{
    public function __construct(){
        parent::__construct();
    }
}

require(APPPATH.'libraries/Public_Controller.php'); // contains some logic applicable only to `public` controllers
require(APPPATH.'libraries/Admin_Controller.php'); // contains some logic applicable only to `admin` controllers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...