简体   繁体   中英

CodeIgniter call protected method of another controller

I have two classes on my Codeigniter project: Users and Profiles

Users:

class Users extends CI_Controller 
{
   ...

Profiles:

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

When a user is created by user controller, a profile should be created immediately. So a function in Users has to call create_user_profile function. Now my question is:

If I make create_user_profile public, one can call it by URL. But if I keep it protected, then how to call it from User controller?

Is there a better way than moving create_user_profile from Profiles controller to Users controller?

Try making a Profiles Library instead :

Libraries/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
    }
  }

controllers/users.php

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

Put it in a different, non-web-controller class. Then you can re-use it from everywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM