LoginSignup
5
5

More than 5 years have passed since last update.

PhalconとMongoDBの俺メモ(1) 登録・検索・更新・削除など

Last updated at Posted at 2016-02-03

先日、MongoDBが面白かったので、Phalcon Framework で使ってみたときのメモ

設定

まず、Phalconのチュートリアル見ながら、スタートアップのDIにMongoDBへの接続とCollection Managerを登録

index.php
    // ローカルホストへの接続
    $di->set('mongo', function () {
        $mongo = new MongoClient();
        return $mongo->test;
    }, true);

    $di->set('collectionManager', function(){
        return new \Phalcon\Mvc\Collection\Manager();
    });

モデルとして、これもチュートリアルに倣って

Item.php
<?php

use Phalcon\Mvc\Collection;

class Item extends Collection
{
    public function getSource()
    {
        return "item";
    }
}

登録

データを登録して表示してみる。

hoge.php
// 登録して
$bat = new Item();
$bat->name = '金属バット';
$bat->type = 'Weapon';
$bat->attackPoint = '3d6';
$bat->save();

$nabe = new Item();
$nabe->name = 'アルミの鍋';
$nabe->type = 'Helmet';
$nabe->defencePoint = 3;
$nabe->save();

$coke = new Item();
$coke->name = '黒い炭酸水';
$coke->type = 'Drink';
$coke->recoveryPoint = 7;
$coke->save();

// 表示
$items = Item::find();
foreach ($items as $item) {
    echo $item->name . "<br>";
}

削除

データを削除して表示してみる。

moge.php
// 削除してみて
$items = Item::find();
foreach ($items as $item) {
    $item->delete();
}

// 表示
$items = Item::find();
foreach ($items as $item) {
    echo $item->name . "<br>";
}

更新

データを更新して表示してみる。

poge.php
// 更新してみて
$items = Item::find();
foreach ($items as $item) {
    $item->name = "「" . $item->name . "」";
    $item->save();
}

// 表示
$items = Item::find();
foreach ($items as $item) {
    echo $item->name . "<br>";
}

検索

特定のデータを更新して表示してみる。

toge.php
// 特定のデータを更新してみて
$items = Item::find([['type' => 'Drink']]);
foreach ($items as $item) {
    $item->name = '黒っぽい炭酸水';
    $item->save();
}

// 表示
$items = Item::find();
foreach ($items as $item) {
    echo $item->name . "<br>";
}

なるほど。

5
5
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
5
5