FuelPHPをやってみる (1) - Getting Start -

2012-11-04T00:00:00+00:00 FuelPHP PHP

とりあえずなんかやってみようと

fuel/app/config/routes.phpを設定

ルーティングを何やら設定出来る模様

<?php

return array(
    "_root_" => "home/index",
    "_404_" => "error/404",
    "sample/(:num)" => array(
        array(
            "GET", new Route("sample/index/$1")
        )
    )
);

_root_でルートなコントローラーアクションを指定出来る。詳しいことは http://docs.fuelphp.com/general/routing.html を読んだ方が早いかも

fuel/app/classes/controller/home.php

<?php

class Controller_Home extends Controller {
    public function action_index() {
        return Response::forge("hoge");
    }
}

書いたら前回書いたようにfpm+Nginxで動かしてるのでhttp://localhostにアクセスすると画面にはhogeと出る

fuel/app/classes/controller/error.php

<?php

class Controller_Error extends Controller {
    public function action_404() {
        return new Response("404 Not Found", 404);
    }
}

HTTP404 Errorなページのアクションコントローラーを定義。で404を送出するような場合において

throw new HttpNotFoundException();

だと問題無いけど

return new Response("not found", 404);

とするとController_Error#action_404には及ばない模様

fuel/app/classes/controller/sample.php

<?php

class Controller_Sample extends Controller {
    public function action_index($id = 0) {
        if ($this->request->get_method() === "GET") {
            if ($id > 0 && $id % 2 == 0) {
                $data["message"] = "hoge fuga foobar";

                return View::forge("sample/index", $data);
            }
        }

        throw new HttpNotFoundException();
    }
}

$dataに展開したデータは引数のキーが変数名となってビューで使用可能な感じな模様。でリクエストメソッドをチェックしている訳はあとで説明する。でリクエストの要件に合わない場合はHttpNotFoundExceptionがスローされるようにする

fuel/app/views/sample/index.php

<html>
  <body>
    <?php echo $message; ?>
  </body>
</html>

fual/app/tests/controller/sample/test_index.php

<?php

class Test_Controller_Sample extends TestCase {

    protected function setUp() {
        parent::setUp();
    }

    /**
     * @expectedException HttpNotFoundException
     */
    public function test1ActionIndex() {
        Request::forge("sample/index")->set_method("GET")->execute(
            array(1)
        )->response();
    }

    /**
     * @expectedException HttpNotFoundException
     */
    public function test2ActionIndex() {
        Request::forge("sample/index")->set_method("POST")->execute(
            array(2)
        )->response();
    }

    public function test3ActionIndex() {
        $res = Request::forge("sample/index")->set_method("GET")->execute(
            array(2)
        )->response();

        $this->assertEquals(200, $res->status);
        $this->assertEquals("hoge fuga foobar", $res->body->message);
    }
}

まぁPHPUnitベースでテストを書けるんですが、コントローラーテストをする際にルーティングではGETのみって定義した場合にset_method("POST")等をしてもルーティングがコントローラーまで届いてしまう。これちょっと原因がよく分かってない。

でHttpNotFoundExceptionがスローされても_404_なハンドラーとか作用しないんで、例外が起きるっていうのを前提にしたexpectedを指定しなきゃならん模様。

一応、こんな感じでコントローラーテスト出来る模様。ちょっとまだ微妙なので色々判明次第追記する予定

ってな感じでFuelPHPの(標準的な?)コントローラーの作り方は以上な感じ

追記

デフォルトでログの出力レベルだとか、ログのタイムゾーンがen_USベースな模様。なので以下のようにfuel/app/config/config.phpを修正

<?php

return array(
    "base_url"  => null,
    "url_suffix"  => null,

    // 空にしないとResponse::redirect時に/index.phpベースでリダイレクトされる模様なので、問題無ければ消しておく
    "index_file"  => "",

    "profiling"  => false,

    "cache_dir"       => APPPATH."cache/",

    "caching"         => false,
    "cache_lifetime"  => 3600, // In Seconds

    "ob_callback"  => null,

    "errors"  => array(
        "continue_on"  => array(),
        "throttle"     => 10,
        "notices"      => true,
    ),

    "language"           => "ja",
    "language_fallback"  => "ja",
    "locale"             => "ja_JP.utf8",
    "encoding"  => "UTF-8",
    "server_gmt_offset"  => 0,

    // タイムゾーンを変える
    "default_timezone"   => "Asia/Tokyo",

    // 出力されるログレベルを変える
    "log_threshold"    => Fuel::L_ALL,

    "log_path"         => APPPATH."logs/",
    "log_date_format"  => "Y-m-d H:i:s",

    "security" => array(
        "csrf_autoload"    => true,
        "csrf_token_key"   => "fuel_csrf_token",
        "csrf_expiration"  => 0,
        "uri_filter"       => array("htmlentities"),

        "input_filter"  => array(),
        "output_filter"  => array("Security::htmlentities"),
        "auto_filter_output"  => true,
        "whitelisted_classes" => array(
            "FuelCoreResponse",
            "FuelCoreView",
            "FuelCoreViewModel",
            "Closure",
        )
    ),

    "cookie" => array(
        "expiration"  => 0,
        "path"        => "/",
        "domain"      => null,
        "secure"      => false,
        "http_only"   => true,
    ),

    "validation" => array(
        "global_input_fallback" => true,
    ),

    "routing" => array(
        "case_sensitive" => true,
    ),

    "module_paths" => array(
    ),

    "package_paths" => array(
    ),


    "always_load"  => array(
        "packages"  => array(
            "orm",
        ),
        "modules"  => array(),
        "classes"  => array(),
        "config"  => array(),
        "language"  => array(),
    ),
);

fpmプロセスを再起動する fpmでFuelPHP