Welcome Guest, Not a member yet? Register   Sign In
The constructor method - Good practice?
#1

[eluser]Petsoukos[/eluser]
Hello,

Is it good practice to use the __construct() to trigger the autologin* system? I mean I have a bit over 2 years experience with PHP but today it occurred to me to have the constructor do this work and not every single method in the class.

Code:
class Home extends CI_Controller {
    
    function __construct() {
        parent::__construct();
        $this->load->model('user_model');
        $this->user_model->AutoLogin();
    }

}

Thanks.



* My custom autologin
#2

[eluser]Isern Palaus[/eluser]
I think that yes. It will be better if you do it in a base controller, so you can extend this controller on your Home, Pages, Contact, etc. controllers.

In CI 2.0 create a MY_Controller in /application/core like:

Code:
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

class MY_Controller extends CI_Controller
{
    
    public function __construct()
    {
        parent::__construct();
        
        $this->load->model('user_model');
        $this->user_model->AutoLogin();
    }
    
}

And then:

Code:
<?php
class Home extends MY_Controller {
    
    function __construct() {
        parent::__construct();
    }

}
?>
#3

[eluser]Petsoukos[/eluser]
Thanks for the quick answer! Smile

This way makes more sense and my application became easier to maintain now!
#4

[eluser]Phil Sturgeon[/eluser]
If you have a frontend and a backend you may want different logic for each, so you can make different base controllers instead of just the one:

http://philsturgeon.co.uk/news/2010/02/C...ing-it-DRY
#5

[eluser]Petsoukos[/eluser]
Yes it's a bit tricky. I have a front-end and a back-end (different application folder).

Access in the public front-end differs from page to page.

e.g. The Home can be accessed even when your session is set by the autologin cookie, but you can't access the edit profile, private info section or private messages with that session. You need a session that's been created with "hard" login.

I'll figure it out.

Thanks for the link! It's a good read! Wink




Theme © iAndrew 2016 - Forum software by © MyBB