【问题标题】:CodeIgniter call protected method of another controllerCodeIgniter 调用另一个控制器的受保护方法
【发布时间】:2013-06-26 16:52:08
【问题描述】:

我的 Codeigniter 项目中有两个类:Users 和 Profiles

用户:

class Users extends CI_Controller 
{
   ...

个人资料:

class Profiles extends CI_Controller 
{
   protected function create_user_profile()
   {
      ....
   }
   ...

当用户控制器创建用户时,应立即创建配置文件。所以用户中的一个函数必须调用create_user_profile函数。现在我的问题是:

如果我将create_user_profile 公开,则可以通过 URL 调用它。但是如果我保持它受到保护,那么如何从用户控制器调用它?

有没有比将 create_user_profile 从 Profiles 控制器移动到 Users 控制器更好的方法?

【问题讨论】:

    标签: php codeigniter


    【解决方案1】:

    尝试制作个人资料库:

    库/profiles.php

    class Profiles 
      {
        protected $CI;
    
        public function __construct()
        {
          $this->CI =& get_instance(); // Existing Code Igniter Instance
        }
    
        public function create_user_profile()
        {
          // Your Code Here
          // can communicate back with CI by using $this->CI
          // $this->CI->load->view(....);
          // $this->CI->load->model(...);
          // ETC
        }
      }
    

    控制器/users.php

    class Users extends CI_Controller 
      {
        public function my_function(){
          $this->load->library('profiles');
          $this->profiles->create_user_profile();    
        }
      }
    

    【讨论】:

    • 您也可以使用模型,但我同意库似乎是这里的最佳选择。
    • 我的控制器有错别字,呵呵,只是为了避免混淆。我是 Codeigniter 的大用户,发现自己为几乎所有东西构建库。将我的模型留给数据库模板。
    • 谢谢@BadWolf,我从users控制器调用了profile模型,不再需要从profile控制器调用任何方法。
    【解决方案2】:

    把它放在一个不同的、非网络控制器的类中。然后你可以在任何地方重复使用它。

    【讨论】:

    • 什么是非web-controller类?
    • 不扩展 CI_Controller 的泛型类
    • 那么从中调用模型会更难
    • 然后将模型作为参数传递给方法
    • 有没有办法将其公开但阻止用户从 url 调用?
    猜你喜欢
    • 2011-09-23
    • 2020-08-02
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    相关资源
    最近更新 更多