在CodeIgniter中调用另一个控制器中的控制器功能 [英] Calling a Controller function in another Controller in CodeIgniter

查看:1462
本文介绍了在CodeIgniter中调用另一个控制器中的控制器功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的codeigniter应用程序中有一个控制器用户。此控制器有一个名为 logged_user_only()的函数:

I have a controller "user" in my codeigniter application. This controller has a function called logged_user_only():

public function logged_user_only()
    {
        $is_logged = $this -> is_logged();
        if( $is_logged === FALSE)
        {
            redirect('user/login_form');
        }
    }

由于此函数调用另一个函数 is_logged(),只是检查会话是否已设置,如果是则返回true,否则返回false。

As this function calls another function called is_logged(), which just checks if the session is set, if yes it returns true, else returns false.

将此函数放在同一控制器中的任何函数的开始,它将检查用户是否未记录,它将重定向到 login_form 否则继续。这工作正常。
例如,

Now if i place this function in the begining of any function within same controller, it will check if the user is not logged, it will redirect to login_form otherwise continue. This works fine. For example,

public function show_home()
    {
        $this -> logged_user_only();
        $this->load->view('show_home_view');
    }



现在我想把这个 logged_user_only 函数在另一个控制器的功能中检查用户是否登录?

Now I would like to call this logged_user_only() function in a function of another controller to check if the user is logged in or not?

PS。如果这不能做,或不推荐,我应该在多个控制器中访问这个功能应该在哪里?感谢。

PS. If this can not be done, or is not recommended, where should i place this function to access in multiple controllers? Thanks.

推荐答案

为什么不扩展控制器,所以登录方法是在MY控制器和所有其他控制器扩展这一点。例如你可以有:

Why not extend the controllers so the login method is within a MY controller (within the core folder of your application) and all your other controllers extend this. For example you could have:

class MY_Controller extends CI_Controller {
    public function is_logged()
    {
        //Your code here
    }
}

控制器可以扩展如下:

class Home_Controller extends MY_Controller {
    public function show_home()
    {
         if (!$this->is_logged()) {
           return false;
         }
    }
}

a href =http://ellislab.com/codeigniter/user-guide/general/core_classes.html>创建核心系统类

For further information visit: Creating Core System Classes

这篇关于在CodeIgniter中调用另一个控制器中的控制器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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