FuelPHPをやってみる (2) - データベースを使う -

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

タイトル通りデータベースを使う

設定

デフォルトで使用されるenvironmentがdevelopmentになっているので、fuel/app/config/development/db.phpの設定を変える。但し、oil test時はtestになるので注意

<?php

return array(
    "default" => array(
        "connection" => array(
            "dsn" => "mysql:host=127.0.0.1;dbname=sample",
            "username" => "user",
            "password" => "pass",
        ),
    ),
);

で単体テストする際に必要になるので、fuel/app/config/testディレクトリを作ってそこにdb.phpを同じように作っておく

fuel/app/classes/model/items.php

fuel/app/classes/modelな所に作る。で一応、Modelっていうクラスもあるんだけど

<?php

namespace Fuel\Core;

class Model
{

}

っていうのになってて特にメソッドがある訳じゃないので、別に継承しなくても良いんじゃねっていうか継承する必要があるのかが微妙なのでそこは放置する

とりあえず、namespaceでModelを定義するかクラス名の接頭辞にModel_を付けて定義すれば良い模様

<?php

class Model_Items {
    public static function findAll() {
        $entries = array();

        try {
            /* SQLを書いて取得する場合
            $query = DB::query("SELECT id,item_name FROM items");
            $result = $query->execute();
            $entries = $result->as_array();
            */

            // QueryBuilderを使って取得する場合
            $query = DB::select(
                "i.id",
                "i.item_name",
                DB::expr("count(s.id) as count")
            )->from(
                array("items", "i")
            )->join(
                array("sales", "s"),
                "INNER"
            )->on(
                "i.id", "=", "s.item_id"
            )->group_by(
                "s.item_id"
            )->order_by("count", "ASC");

            // SELECT `i`.`id`, `i`.`item_name`, count(s.id) as count FROM `items` AS `i` INNER JOIN `sales` AS `s` ON (`i`.`id` = `s`.`item_id`) GROUP BY `s`.`item_id` ORDER BY `count` ASC
            Log::info($query->compile());

            $result = $query->execute();
            $entries = $result->as_array();
        } catch (Database_Exception $e) {
            Log::error($e);
        }

        return $entries;
    }
}

fuel/app/classes/controller/home.php

<?php

class Controller_Home extends Controller {
    public function action_index() {
        $data["entries"] = Model_Items::findAll();

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

な感じで普通に作ったモデルクラスを呼びだせば良い

fuel/app/tests/model/items.php

<?php

class Test_Model_Items extends TestCase {
    protected function setUp() {
        parent::setUp();
    }

    public function test_findAll() {
        $entries = Model_Items::findAll();
        $this->assertNotNull($entries);
        $this->assertTrue(count($entries) > 0);
    }
}

上記でも書いたようにoil test時にはenvironmentがtestになるので、定義ファイルの設定を忘れずに

FuelPHPをやってみる (3) - Model_Crudを使う - fpmプロセスを再起動する