NanoA でカウンタを書けるようにした

? load_plugin('counter')
<!doctype html>
<h1>ぼくのほーむーぺーじ</h1>

現在の訪問者数は: <?= counter_increment() ?>人です。

</html>

こんな感じでかけます。とても簡単だね。

http://d.hatena.ne.jp/tokuhirom/20081117/1226922006

PHP インスパイヤNanoA では、以下のように書けるようにしました。プラグインの宣言とか不要。

<!doctype html>
<h1>ぼくのほーむーぺーじ</h1>

現在の訪問者数は: <?= $app->render('system/plugin/counter') ?>人です。

</html>

ちなみに、カウンタの実装コードは、こんな感じです。コメントと空行除けば、たった10行。簡単ですね。

package system::plugin::counter;

sub run_as {
    my ($klass, $app, $c) = @_;
    
    # 指定された名前、あるいはコントローラのパッケージ名を名前に使う
    my $counter_name = $c && $c->{name} || ref $app;
    $counter_name =~ s/::/./g;
    
    # カウンタの値を設定データベースからロード
    my $cnt = $app->config->prefs("counter.$counter_name") || 1;
    
    # +1 した値を保存
    $app->config->prefs("counter.$counter_name", $cnt + 1);
    
    # カウンタの値を返す
    $cnt;
}

1;