【问题标题】:Codeigniter routing, setting custom controllers directory based on a session userdataCodeigniter 路由,根据会话用户数据设置自定义控制器目录
【发布时间】:2014-01-04 13:10:52
【问题描述】:

有没有办法根据会话数据在 CI 中进行路由。

例如:

CI
 |-controllers
 |       |------student
 |       |         |--dashboard.php
 |       |         |--marks.php
 |       |
 |       |------teacher
 |       |         |--dashboard.php
 |       |         |--marks.php
 |...

这样

if ($this->session->userdata('type') == 'student')

http://localhost/CI/dashboard 将路由到控制器/学生/仪表板

else if($this->session->userdata('type') == 'teacher')

http://localhost/CI/dashboard 将路由到控制器/教师/仪表板

【问题讨论】:

    标签: php codeigniter url-routing


    【解决方案1】:

    如果文件夹结构将完全相同(如您在 Q 中描述的),并且您不需要用户查看他所在的部分(teacher/dashboard、 student/dashboard),根本不需要任何路由。

    使用您提供的逻辑并简单地加载不同的视图

    例如。制作函数

    function _render( $view_file = 'dashboard', $data ) {
    
        if ($this->session->userdata('type') == 'student') {
            $this->load->view('/student/'. $view_file, $data);
        } else {
            $this->load->view('/teacher/'. $view_file, $data);
        }
    
    }
    

    注意:使用控制器上方的方法会很长,因为您必须同时拥有教师/学生的功能,上方的方法只是区分视图文件

    如果您想确保您的网址看起来像 /teacher/dashboard... 和 student/dashboard

    我会选择这种方法

    用这个tutorial扩展CI_Controller。

    并且在构造函数中确保你重定向到你想要go重定向的地方

    (在 MY_Controller.php 中)

    function __construct() {
    
        parent::__construct();
        if ($this->uri->segment(1) === FALSE) {//segment 'teacher' or 'student' doesnt exists
            if ($this->session->userdata('type') == 'student') {
                redirect('/student/dashboard');
            } else if($this->session->userdata('type') == 'teacher') {
                redirect('/teacher/dashboard');
            } else {
               //default action
            }
    
        } else {
    
            if ($this->uri->segment(1) != $this->session->userdata('type')) {
            //something is not right, session do not match the segment
            //logout or redirect to right segment
                redirect($this->session->userdata('type').'/dashboard');
            }
            //else is not needed code continues no redirects are needed
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多