MY_Controller.phpでよりDRYなコードを書く をもうちょっと改造してみた
シンプルで良いので、さらに拡張してみた。
元ネタ
http://www.e2esound.com/wp/2011/03/29/how_to_extends_controller_to_coding_dry/
私はCodeIgnitorを使っておきながら、普通のHTMLを表示させるだけも多いので、
MY_Controllerを拡張して、ビューファイルがある場合は自動で表示させることにしてみた。
ただし、条件として、「class/method」と「views/class/method」は名前を合わせる必要があります。
<?php class MY_Controller extends CI_Controller { public function __construct() { parent::__construct(); } function _remap($method){ if(method_exists($this, $method)){ $this->$method(); } else { //ビューを探す $view_file = FCPATH.APPPATH.'views/' .strtolower(get_class($this)).'/'.$method.'.php'; if(file_exists($view_file)){ $this->view(strtolower(get_class($this)).'/'.$method); } else { show_404(); } } } // The easy way to use model in controller // http://elliotscode.com/2011/03/28/codeigniter-my-controller/ protected function model($name) { $name = $name . '_model'; if( ! isset($this->{$name})) { $this->load->model($name); } return $this->{$name}; } //The easy way to call view in controller protected function view($name, $data = array(), $return = FALSE) { $name = $name . '_view'; return $this->load->view($name, $data, $return); }