codeigniterで共通のヘッダーフッターの読み出しはCI_LoaderをextendsしたMY_Loaderで実装する

CodeIgniter PHP

small__9257451603

codeigniterで共通のヘッダー、フッターを読み込むときは、CI_LoaderクラスをextendsしたMY_Loaderクラスで行うのがよいと思いました。

まずはhookでやってみた

codeigniterではhookというコントローラの直前や直後など実行したいタイミングを選べる機能が用意されています。

具体的に、application/config/hooks.php でコントローラがインスタンス化された直後でヘッダーを読み込み、コントローラが完全に実行された直後でフッターを読み込むように対応してみました。

$hook['post_controller_constructor'][] = array(
		'class'    => 'HeaderFooterSet',
		'function' => 'beforeFilter',
		'filename' => 'headerfooterset.php',
		'filepath' => 'hooks'
);

$hook['post_controller'][] = array(
		'class'    => 'HeaderFooterSet',
		'function' => 'afterFilter',
		'filename' => 'headerfooterset.php',
		'filepath' => 'hooks'
);

クラスファイル application/hooks/headerfooterset.php に以下のように実装してみます。

class HeaderFooterSet {
 function __construct() {
 $this->ci =& get_instance();
 }

 public function beforeFilter()
 {
 // 共通ヘッダー
 $ci =& get_instance();
 $ci->load->view('header');
 }

 public function afterFilter()
 {
 // 共通フッター
 $ci =& get_instance();
 $this->ci->output->set_header('Content-Type: text/html; charset=utf-8');
 $ci->load->view('footer');
 }
}

application/views/header.php が共通のヘッダーのviewですが、、コントローラがインスタンス化された直後で実行するため、コントローラ内で実行された値をapplication/views/header.php で呼び出すことができないため不都合になるケースがあります。

hookはやめてMY_Loaderでやってみた

view関数を読み込む直前でheader、直後でfooterを読み込めるようにしたい。具体的には下記Welcomeクラスのview関数でwelcome_viewを読み込んでいますが、この直前、直後でheader、footerが呼び出せればコントローラ内で実行された値を呼び出せます。以下の例ですとview_typeをheader内で表示させることが可能になります。

class Welcome {
	public function index()
	{
		$data = array();
		$data["view_type"] = "welcome_view";
		$this->load->view('welcome_view', $data);
	}
}

CI_LoaderをextendsしたMY_Loaderクラスを作成して、以下のように実装することでコントローラ内で実行された値をheaderやfooterで読み出せることができました。

class MY_Loader extends CI_Loader {
	function __construct(){
		parent::__construct();
		$this->header_path = APPPATH . "views/header.php";
		$this->footer_path = APPPATH . "views/footer.php";
	}

	public function set_header($view)
	{
		$this->header_path = APPPATH . "views/".$view.".php";
	}

	public function set_footer($view)
	{
		$this->footer_path = APPPATH . "views/".$view.".php";
	}

	public function view($view, $vars = array(), $return = FALSE)
	{
		$ci =& get_instance();
		$class = $ci->router->fetch_class(); // Get class
		$action = $ci->router->fetch_method(); // Get action

		$header =  $this->_ci_load(array('_ci_path' => $this->header_path, '_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
		$body =  $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
		$footer =  $this->_ci_load(array('_ci_path' => $this->footer_path, '_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
		if($return) {
			return $body;
		}
	}
}

関連記事

コメント

この記事へのコメントはありません。

カテゴリー

お問い合わせはコチラ!