FuelPHP のサンプルアプリ「Stationwagon」をみてみる

鉄は熱いうちに打て-コピペプログラマーのためのFuelPHP動作実験その1(サンプルソース&お砂場づくり) - ヌル日記 を参考に FuelPHP でのサンプルアプリ「Stationwagon」をインストールして研究してみましょう。

インストールする

Git でソースコードをサクッと取得。

$ git clone git://github.com/abdelm/stationwagon.git

ログなどを PHP から書き込みできるようにパーミッションを設定します。

$ cd stationwagon
$ oil r install

stationwagon/public/ を Web からアクセス可能にします。

$ sudo ln -s /path/to/satationwagon/public /opt/lampp/htdocs/stationwagon

FuelPHP を設定する

設定ファイル config.php を変更します。

--- a/fuel/app/config/config.php
+++ b/fuel/app/config/config.php
@@ -41,7 +41,7 @@ return array(
         *
         * Set this to false or remove if you using mod_rewrite.
         */
-       'index_file'  => 'index.php',
+       'index_file'  => '',
 
        'profiling'  => false,
 
@@ -71,7 +71,7 @@ return array(
         */
        'language'           => 'en', // Default language
        'language_fallback'  => 'en', // Fallback language when file isn't available for default language
-       'locale'             => 'en_US', // PHP set_locale() setting, null to not set
+       'locale'             => 'ja_JP.utf8', // PHP set_locale() setting, null to not set
 
        'encoding'  => 'UTF-8',
 
@@ -81,8 +81,8 @@ return array(
         * server_gmt_offset    in seconds the server offset from gmt timestamp when time() is used
         * default_timezone             optional, if you want to change the server's default timezone
         */
-       'server_gmt_offset'  => 0,
-       'default_timezone'   => 'UTC',
+       'server_gmt_offset'  => 3600 * 9,
+       'default_timezone'   => 'Asia/Tokyo',
 
        /**
         * Logging Threshold.  Can be set to any of the following:
@@ -94,7 +94,7 @@ return array(
         * Fuel::L_INFO
         * Fuel::L_ALL
         */
-       'log_threshold'    => Fuel::L_WARNING,
+       'log_threshold'    => Fuel::L_ALL,
        'log_path'         => APPPATH.'logs/',
        'log_date_format'  => 'Y-m-d H:i:s',
 

(2013/3/9 追記) 上記、server_gmt_offset の変更はサーバ設定が適切な場合は不要です。http://letsspeak.hatenablog.com/entry/2013/03/09/160449 参照。

データベースを作成する

専用のデータベースとユーザ stationwagon を作成します。

> CREATE USER 'stationwagon'@'localhost' IDENTIFIED BY '***';

> GRANT USAGE ON * . * TO 'stationwagon'@'localhost' IDENTIFIED BY '***' 
 WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 
 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;

> CREATE DATABASE IF NOT EXISTS `stationwagon` ;

> GRANT ALL PRIVILEGES ON `stationwagon` . * TO 'stationwagon'@'localhost';

database.sql にあるテーブルを作成します。

> CREATE TABLE `sw_users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `password` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
  `email` varchar(70) COLLATE utf8_unicode_ci DEFAULT NULL,
  `profile_fields` text COLLATE utf8_unicode_ci,
  `group` int(11) DEFAULT NULL,
  `last_login` bigint(20) DEFAULT NULL,
  `login_hash` tinytext COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

> CREATE TABLE `sw_articles` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) unsigned NOT NULL DEFAULT '0',
  `category_id` int(11) DEFAULT NULL,
  `title` varchar(140) COLLATE utf8_unicode_ci DEFAULT NULL,
  `body` text COLLATE utf8_unicode_ci,
  `published` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `created_at` bigint(20) unsigned DEFAULT NULL,
  `updated_at` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

> CREATE TABLE `sw_categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) unsigned NOT NULL DEFAULT '0',
  `name` varchar(140) COLLATE utf8_unicode_ci DEFAULT NULL,
  `description` tinytext COLLATE utf8_unicode_ci,
  `created_at` bigint(20) DEFAULT NULL,
  `updated_at` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

データベース接続設定をする

開発環境のデータベース設定ファイル fuel/app/config/development/db.php を以下のように変更します。

データベース設定は config/db.php とマージされ上書きされますので、config/db.php との差分のみを config/development/db.php に記述すれば OK です。

--- a/fuel/app/config/development/db.php
+++ b/fuel/app/config/development/db.php
@@ -7,8 +7,9 @@ return array(
        'default' => array(
                'connection'  => array(
                        'dsn'        => 'mysql:host=localhost;dbname=stationwagon',
-                       'username'   => 'root',
-                       'password'   => '',
+                       'username'   => 'stationwagon',
+                       'password'   => '***',
                ),
+               'table_prefix' => 'sw_',
        ),
 );

Web ブラウザからアクセスしてみる

トップページにアクセスしたところ。


サインアップページ。


登録完了したところ。


ログインしたところ。Articles、Categories、Logout メニューが表示されるようになりました。


カテゴリーページ。


カテゴリーを追加しました。


下書きの記事を追加しました。おっと、HTML タグが使えるようです。

コントローラの構造とユーザのアクセス権

このアプリは FuelPHP に標準で用意されている Controller_Template を継承した Controller_Common クラス(fuel/app/classes/controller/common.php)を作成し、ここの before() メソッドでユーザのアクセス権のチェックを行っています。

<?php

class Controller_Common extends Controller_Template {

	public function before()
	{
		parent::before();

		if ($this->request->action != null)
		{
			$action = array($this->request->action);
		}
		else
		{
			$action = array('index');
		}

		// Check user access
		$access = Auth::has_access(array(
			$this->request->controller,
			$this->request->action
		));

		if ($access != true)
		{
			Response::redirect('users/login');
		}
		else
		{
			if (Auth::check())
			{
				$this->user_id = Auth::instance()->get_user_id();
				$this->user_id = $this->user_id[1];
			}
		}
	}()

リクエストを処理するコントローラはこの Controller_Common クラスを継承して作成されています。

認証ライブラリは、FuelPHP 標準の Auth パッケージの SimpleAuth を使っています。ユーザのアクセス権の設定(アクセスできるメソッド)は、fuel/app/config/simpleauth.php の role に定義されています。

ログインページのバグ修正

ログイン済みでログインページにアクセスすると、redirect が無限ループするバグがありましたので修正しておきます。

--- a/fuel/app/classes/controller/users.php
+++ b/fuel/app/classes/controller/users.php
@@ -58,6 +58,12 @@ class Controller_Users extends Controller_Common {
    
    public function action_login()
    {
+       // Already logged in?
+       if (Auth::check())
+       {
+           Response::redirect('users');
+       }
+       
         // Setup Validation
         $val = Validation::factory('login_user');
 
--- a/fuel/app/config/simpleauth.php
+++ b/fuel/app/config/simpleauth.php
@@ -69,6 +69,7 @@ return array(
         ),
         'user'       => array(
             '\Controller_Users'  => array(
+               'login',
                 'logout',
             ),
             '\Controller_Articles'   => array(

FuelPHP のサンプルアプリ「Stationwagon」をみてみる その2 へ続く。