Codeigniter和代码重复DRY

时间:2016-03-11 10:55:13

标签: php codeigniter

需要最佳做法以避免Codeigniter类方法中的代码重复。这在我的情况下甚至可能吗?如果我以某种方式分配全局变量,我仍然需要传递$ data数组来查看,所以也许某种全局$ data数组?

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);
}

2 个答案:

答案 0 :(得分:1)

这应该有效:

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);
}

答案 1 :(得分:0)

如下:

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);
}