CodeIgniter扩展多个控制器?

use*_*439 7 php inheritance codeigniter multiple-inheritance out-of-memory

找不到办法做到这一点,可能是因为有另一种方法可以做到这一点?

我的一些控制器扩展了AdminLayout,其中一些扩展了ModLayout,但我还需要这些页面来扩展LoggedIn控制器.

class Profile extends AdminLayout, LoggedIn {
Run Code Online (Sandbox Code Playgroud)

然而,调查没有办法很好地做到这一点.有解决方法吗?

Roo*_*eyl 25

假设您使用的是Codeigniter 2,可以通过将所有扩展控制器类放在同一个文件中来完成.

/ application/core中创建一个名为MY_Controller.php的文件(不要忘记在第109行的config.php中检查子类前缀)

在这里,您可以添加所有要扩展的控制器类.例如;

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * MY_Controller Class
 *
 *
 * @package Project Name
 * @subpackage  Controllers
 */
class MY_Controller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->form_validation->set_error_delimiters('<div class="form-error">', '</div>');
    }
}

class LoggedIn extends MY_Controller {

    public function __construct() {
        parent::__construct();
        if (is_logged_in() == FALSE) {
            $this->session->set_userdata('return_to', uri_string());
            $this->session->set_flashdata('message', 'You need to log in.');
            redirect('/home');
        }
    }
}

class AdminLayout extends LoggedIn {

    public function __construct() {
        parent::__construct();
        // do something
    }
}

class ModLayout extends LoggedIn {

    public function __construct() {
        parent::__construct();
        // do something
    }
}

/* End of file  */
/* Location: ./application/core/ */
Run Code Online (Sandbox Code Playgroud)

然后,当您按照正常情况创建控制器时,只需选择要扩展的基本控制器类.例;

class Foo extends AdminLayout {

    public function __construct() {
        parent::__construct();
        if (is_logged_in() == FALSE) {
            $this->session->set_userdata('return_to', uri_string());
            $this->session->set_flashdata('message', 'You need to log in.');
            redirect('/home');
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要么

class Bar extends ModLayout {

    public function __construct() {
        parent::__construct();
        if (is_logged_in() == FALSE) {
            $this->session->set_userdata('return_to', uri_string());
            $this->session->set_flashdata('message', 'You need to log in.');
            redirect('/home');
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 2

PHP 不支持多重继承。您可以使用 Codeigniter 帮助程序或库来实现此目的。

看一下库示例:

http://codeigniter.com/wiki/Simplelogin