ぜんぶなんとかなる

ふしみの雑文

codeIgniter + twig + tank_auth

phpフレームワーク「codeIgniter」を使ってメモアプリを作る過程。

  • php 5.3.8
  • codeIgniter 2.0.3
  • twig 1.3.0
  • tank_auth 1.0.9
CodeIgniter をダウンロード

ダウンロード - CodeIgniter日本語化 - SourceForge.JP

以下の2ファイルを中心に編集、設置。

  • Application/config/config.php
  • Application/config/database.php

welcome message 出るところまでやる。

tank_auth をインストール

codeIgniter はすごくシンプルなフレームワークなのだけど、認証周りのモジュールは用意されていないので、サードパーティのライブラリがいくつか存在する。tank_authはその中でも定評のあるライブラリ。

  • ユーザ名・パスワードのバリデーション
  • パスワードのストレッチング
  • CAPTCHA の自動生成・確認 (reCAPTHCA にも対応)
  • メールアドレス確認メールの送信
  • アカウントban

などなど

Tank Auth: Authentication library for CodeIgniter

これも指示に従って設置。…が、しかしcaptchaの画像が出ない。こまった。

/*
|--------------------------------------------------------------------------
| reCAPTCHA
|
| 'use_recaptcha' = Use reCAPTCHA instead of common captcha
| You can get reCAPTCHA keys by registering at http://recaptcha.net
|--------------------------------------------------------------------------
*/
$config['use_recaptcha'] = TRUE;
$config['recaptcha_public_key'] = 'hoge';
$config['recaptcha_private_key'] = 'hoge';

あっさり諦めて、オリジナルのCAPTCHAは使わず、reCAPTCHA を有効にする。できた。

reCAPTCHAはこんなやつ。

Twig をインストール

CodeIgniter はテンプレートエンジンが付属していない。「テンプレートエンジンは重いから生のphpコード書こうぜ」という主張はごもっともなんだが、エスケープ漏れのチェックとかめんどくさい。イイカンジのテンプレートエンジンないかな、と探してたどりついたのが「twig」。

Twig for Template Designers - Documentation - Twig - The flexible, fast, and secure PHP template engine

Twig は継承できるテンプレートエンジン。全体的に「良いSmarty」。

http://fukata.org/2010/07/04/codeigniter-with-twig-1: title

ここらへんを参考につなぎこむ。但し、Libraries/Twig.phpに、Twigの「Autoloader.php」をロードしている箇所があり、PEARの Autoloader.php を先に拾ってしまうので、以下のように改変する必要があった。

		ini_set('include_path',
//		ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'libraries/Twig');
		'libraries/Twig' . PATH_SEPARATOR . APPPATH . ini_get('include_path'));

//		require_once (string) "Autoloader" . EXT;
		require_once (string) "libraries/Twig/Autoloader" . EXT;
できた

controllers/welcome.php

class Welcome extends CI_Controller
{
	function __construct()
	{
		parent::__construct();

		$this->load->helper('url');
		$this->load->library('tank_auth');
		$this->load->library('twig');
		
		if (!$this->tank_auth->is_logged_in()) {
			redirect('/auth/login/');
		} else {
			$query = $this->db->query('SELECT * FROM users where id = "'.$this->tank_auth->get_user_id().'"');
			if($row = $query->row()){
				$this->user = $row;
			}else{
				serverError("ユーザが見つかりません");
			}
		}
	}

	function index()
	{
		$data['user']	= $this->user;
		$this->twig->view('welcome.html', $data);
	}
}

views/welcome.html

email : <strong>{{ user.email }}</strong>

<a href="/auth/logout">logout</a>