LoginSignup
1
1

More than 5 years have passed since last update.

ebiでORM

Last updated at Posted at 2015-12-04

ebiはORMとしてDaoモデルが用意されています。ActiveRecordスタイル”ではありませんが”シンプルにデータベースとやり取りすることが出来ます。

最初にモデルを定義します。ここでは libs/model に User.phpモデルを定義してみましょう。

User.php
<?php
namespace model;

class User extends \ebi\Dao{
    protected $id;
    protected $name;
}

Daoモデルにどのテーブルを使用するか指定していないことに注目してください。Daoモデルには少しだけ規約があり、そのうちの一つは「データベース名はモデル名」というものです。単純でしょう!
お好みのデータベース管理ツールを使い、userテーブルに数行のデータをインサートしてください。Daoで取得し、ビューに渡してみましょう。

では、routes.php を開き(または作成し)ルートを定義してください。

routes.php
<?php
include('ebi.phar');

\ebi\Flow::app([
    'users'=>[
        'action'=>function(){
            $users = \model\User::find_all();

            return ['users'=>$users];
        },
        'template'=>'users.html'
    ]
]);

これは、最初にfind_allメソッドをUserモデルに使用し、userテーブルから全レコードを取得します。
次に取得したレコードを連想配列で名前をつけてreturnします。returnされた連想配列はビュー(tempalte)で使用できる変数となります。

データの表示

では users をビューで使用してみましょう。

resources/templates/users.html
<html>
<body>
<table rt:param="{$users}" rt:var="user">
<thead>
<tr>
    <th>id</th>
    <th>name</th>
</tr>
</thead>
<tbody>
<tr>
    <td>{$user.id()}</td>
    <td>{$user.name()}</td>
</tr>
</tbody>
</table>
</body>
</html>

echo文はどこかと不思議に思えるでしょう。用意されたTemplateを使えば中括弧で囲んだ変数/メソッドをecho出来ます。
Webブラウザーで routes.php/users へアクセスすればレスポンスとしてユーザー達の名前が表示されます。

スクリーンショット 2015-12-05 5.41.41.png

参考:
https://github.com/tokushima/ebi
http://readouble.com/laravel/4/2/0/ja/quick.html

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1