Reputation: 4129
Need best practice to avoid code repetition in Codeigniter Class methods. Is this even possible in my situation? If I somehow assign global variable, I still need to pass $data array to view, so maybe some kind of global $data array?
public function __construct() {
parent::__construct();
}
public function login()
{
$data['title'] = 'User Login';
$data['home_url'] = base_url();
$data['current_url'] = $this->uri->segment(1);
$data['login_url'] = LOGIN_URL;
$data['register_url'] = REGISTER_URL;
$this->parser->parse("login.tpl", $data);
}
public function register()
{
$data['title'] = 'User Register';
$data['home_url'] = base_url();
$data['current_url'] = $this->uri->segment(1);
$data['login_url'] = LOGIN_URL;
$data['register_url'] = REGISTER_URL;
$this->parser->parse("register.tpl", $data);
}
Upvotes: 0
Views: 56
Reputation: 20737
This should work:
private $data = array();
public function __construct() {
parent::__construct();
$this->data['home_url'] = base_url();
$this->data['current_url'] = $this->uri->segment(1);
$this->data['login_url'] = LOGIN_URL;
$this->data['register_url'] = REGISTER_URL;
}
public function login()
{
$this->data['title'] = 'User Login';
$this->parser->parse("login.tpl", $this->data);
}
public function register()
{
$this->data['title'] = 'User Register';
$this->parser->parse("register.tpl", $this->data);
}
Upvotes: 1
Reputation: 44110
How about something like:
public function login()
{
login_or_register("login");
}
public function register()
{
login_or_register("register");
}
public function login_or_register(type)
{
$data['title'] = 'User ' . ucfirst($type);
$data['home_url'] = base_url();
$data['current_url'] = $this->uri->segment(1);
$data['login_url'] = LOGIN_URL;
$data['register_url'] = REGISTER_URL;
$this->parser->parse($type . ".tpl", $data);
}
Upvotes: 0