nazolabo

フリーランスのWebエンジニアが近況や思ったことを発信しています。

rhacoでそれっぽいコントローラを書くとどうなる?

http://d.hatena.ne.jp/nazone/20070413/p1よりもう少しrhacoっぽくして説明をわかりやすくしてみました。

内容

以下setup.phpでの初期化が終了している前提で

  • index.phpを作成し、以下の内容を書く
<?php
include_once("__init__.php");
Rhaco::import("generic.Urls");
Rhaco::import("generic.Flow");
Rhaco::import("exception.ExceptionTrigger");
Rhaco::import("exception.model.NotFoundException");

$default_routing = array(null,null,null,"routing",null);
$parser	= Urls::parser(array(
    
    /* add your routing here */
    
    "^(\\w+)\/(\\w+)\/(\\w+)$"=>$default_routing,
    "^(\\w+)\/(\\w+)$"=>$default_routing,
    "^(\\w+)$"=>$default_routing,
    "^$"=>$default_routing,
  ));

$parser->write();

function routing($model, $action, $id) {
    if (is_null($model) || empty($model)) {
        $model = 'default';
    }
    if (is_null($action) || empty($action)) {
        $action = 'index';
    }
    
    $class = $model."Controller";
    Rhaco::import("controllers.".$class);
    if (!class_exists($class)) {
        ExceptionTrigger::raise(new NotFoundException(Message::_("`{1}` in `{2}`",$class,$action)));
        return null;
    }
    
    $flow = new Flow();
    $flow->setTemplate("{$model}/{$action}.html");
    
    $controller = new $class($flow);
    if (!method_exists($controller, $action)) {
        ExceptionTrigger::raise(new NotFoundException(Message::_("`{1}` in `{2}`",$class,$action)));
        return null;
    }
    
    $controller->$action($id);
    
    return $flow->parser();
}
  • library以下にcontrollersというフォルダを作る。
  • controllers以下にsampleController.phpというファイルを以下の内容で作成
<?php

Rhaco::import("generic.Flow");

class sampleController {
  
  var $flow;
  
  function sampleController($flow) {
    $this->flow = $flow;
  }
  
  function index() {
    
    
  }

}
    • コンストラクタ部分は毎回書くとだるいので基底クラスを作るといいと思います
  • resources/templates以下にsampleというフォルダを作り、その中にindex.htmlというファイルを作る。中は
<html>
<body>
sample document
</body>
</html>
    • (何でもいいです)
  • 〜/index.php/sample/indexでアクセス!

解説

generic.Urlsを使ってRailsみたいなコントローラを書くサンプルです。
urlが/:controller/:action/:id形式でアクセスできるようになります。:controllerの部分がxxxControllerのxxxの部分に相当し、:actionがクラスのメソッドに相当し、その引数に:idが渡ります。それ以外の引数はGETやPOSTで取得するか、Urls::parserの引数でカスタマイズする方針です。
rhaco使いたいけどコントローラがなくてよくわかんねーって人はこんな感じで使ってみるといいかもしれません。