我的应用程序中有一个主菜单,它根据我从数据库中的表中验证的用户角色加载,但每次调用新控制器时我都必须重新创建此菜单,这是方法我在做:
用户控制器:
class User extends Ci_Controller {
function __construct(){
parent::__construct();
if (!$this->session->userdata('session_user')) {
$this->session->set_flashdata("mensaje", 'No cuenta con permisos *');
redirect();
$this->session_usuario = 1;
}
$session_data = $this->session->userdata('session_user');
$image = $session_data['img'];
$nickname = $session_data['nick'];
$res = "";
$this->layout->setLayout('layout/admin');
$this->layout->setImage(base_url().$image);
$this->layout->setNick($nickname);
$data['module'] = $this->usuarios_model->seleccionarModulos($session_data['perfil'] );
for ($i=0; $i < count($data['module']) ; $i++) {
$info['functionality'] = $this->usuarios_model->seleccionarFuncionalidades( $session_data['usuario'], $data['module'][$i]['id']);
$data['module'][$i]['route'] = $this->load->view($data['module'][$i]['route'], $info, true);
}
foreach ($data['module'] as $key => $value) {
$res .= $value['route'];
}
$this->layout->setMenu($res);
}
在支持控制器中完全相同:
class Support extends Ci_Controller {
private $user;
private $permiso;
private $order;
function __construct(){
parent::__construct();
if (!$this->session->userdata('session_user')) {
$this->session->set_flashdata("mensaje", 'No cuenta con permisos *');
redirect();
$this->session_usuario = 1;
}
$session_data = $this->session->userdata('session_user');
$image = $session_data['img'];
$nickname = $session_data['nick'];
$res = "";
$this->layout->setLayout('layout/admin');
$this->layout->setImage(base_url().$image);
$this->layout->setNick($nickname);
$data['module'] = $this->usuarios_model->seleccionarModulos($session_data['perfil'] );
for ($i=0; $i < count($data['module']) ; $i++) {
$info['functionality'] = $this->usuarios_model->seleccionarFuncionalidades( $session_data['usuario'], $data['module'][$i]['id']);
$data['module'][$i]['route'] = $this->load->view($data['module'][$i]['route'], $info, true);
}
foreach ($data['module'] as $key => $value) {
$res .= $value['route'];
}
$this->layout->setMenu($res);
}
我知道这是解决这个问题的错误方法,我想改进它并重用代码。
答案 0 :(得分:1)
一个快速的解决方案是创建一个自定义控制器,并让你的所有控制器扩展:
在core
目录中创建一个MY_Controller.php控制器:
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
// your common code here
}
}
所有需要该代码的子控制器:
class User extends MY_Controller
{
public function __construct()
{
parent::__construct();
// this will inherit the MY_Controller constructor
}
}