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

查看:41
本文介绍了在 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. 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
    }
}

然后你的主控制器可以这样扩展它:

and your main controllers could then extend this as follows:

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

欲了解更多信息,请访问:创建核心系统类

For further information visit: Creating Core System Classes

新链接在这里:https://www.codeigniter.com/user_guide/general/core_classes.html?highlight=core%20classes

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

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