Welcome Guest, Not a member yet? Register   Sign In
Not a direct CI question, how to call an object function from another object
#1

[eluser]atno[/eluser]
Hi,

I have a question which is OO relative, i have an object login (
Code:
class Login extends CI_Controller
) which contains a function
Code:
public function is_logged_in(){}
which checks if the user is logged. What i wanna do is access this function from any other object instead of pasting it and have duplicate code. For example i have an object
Code:
class Memberarea extends CI_Controller
i want to be able to do

Code:
public function index(){
            if([b]object_login[/b]->is_logged_in() === true) {
                echo 'hello ' . $this->session->userdata('email');
                $this->load->view('includes/header');
            }else{
                echo 'you don\'t have access here';
            }
    }

cheers
#2

[eluser]Akinzekeel[/eluser]
Not sure if that's the best approach, but here's what I used to do in recent CI projects:

- In application/core create a file MY_Controller.php with class MY_Controller extends CI_Controller
- Put any universally accessible functions into this class
- Instead of "class Memberarea extends CI_Controller" use "class Memberarea extends MY_Controller"
- Now you can use $this->is_logged_in() without having to define this function multiple times
#3

[eluser]atno[/eluser]
[quote author="sHiRoKKo1337" date="1304205769"]Not sure if that's the best approach, but here's what I used to do in recent CI projects:

- In application/core create a file MY_Controller.php with class MY_Controller extends CI_Controller
- Put any universally accessible functions into this class
- Instead of "class Memberarea extends CI_Controller" use "class Memberarea extends MY_Controller"
- Now you can use $this->is_logged_in() without having to define this function multiple times[/quote]

So class
Code:
Login extends CI_Controller
would also be
Code:
class Login extends MY_Controller
and in general every new object will extend
Code:
MY_Controller
?
#4

[eluser]Akinzekeel[/eluser]
Exactly, and put
Code:
public function is_logged_in() { /* your code here... */ }
into MY_Controller only.

All controllers that extend from MY_Controller will inherit its functions and can access them with $this->...
#5

[eluser]atno[/eluser]
Another way might be to create a custom library as mentioned here Creating Libraries and have all custom functions as libraries instead of using MY_Controller.
Can someone confirm?
#6

[eluser]Akinzekeel[/eluser]
Yes you can do that as well. Libraries have the advantage of being easily re-usable in other CI projects because you can simply copy & paste the library file.

Sometimes I find the MY_Controller way a bit more comfortable, but it can be done with a library too.




Theme © iAndrew 2016 - Forum software by © MyBB