1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Eloqunetでmongodbを使う

Posted at

概要

mongodbをDBに使うケースはままあると思います。
LaravelやLumen等と組み合わせて使うのであればEloquentという仕組みで
データの書き込みや取得ができますが、RDBMSのみ。。
そこでmongodbでEqoquentを使えるライブラリを使って、行きたいと思います。後々、
APIサーバーにのっけて行きたいですね。

環境構築

php7のインストール

  • php7.3、php7.3-mbstring、php-7.3-pdo
yum install --enablerepo=remi,remi-php73 php php-mbstring php-pdo

mongodbのインストール

  • mongod
/etc/yum.repos.d/mongodb-org-4.0.repo
[mongodb-org-4.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.0.asc

を作成し、

sudo yum install -y mongodb-org

でインストール

  • php73-php-pecl-mongo
  • php.iniに上記を追記

laravel-mongodbのインストール

  • yumでzip、unzip
  • composer
  • composerでlaravel-mongodbを導入

動作手順

CapsuleManagerで接続する

lavave-mongodbのInstallationを読みながらCapsule manager単体で動作させます。

db-if.php
<?php

require_once './vendor/autoload.php';
use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;

$capsule->addConnection([
    'driver'    => 'mongodb',
    'host'      => 'localhost',
    'port'      => 27017,
    'database'  => 'db',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
]);

// Set the event dispatcher used by Eloquent models... (optional)
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));

// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();

// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();

$capsule->getDatabaseManager()->extend('mongodb', function($config, $name)
{
    $config['name'] = $name;

    return new Jenssegers\Mongodb\Connection($config);
});

eqloqunetを使うユーザークラス

user.php
<?php
require_once './vendor/autoload.php';

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class User extends Eloquent {

    protected $collection = 'users_collection';

}

で、これらを使って書き込みをします。

write-test.php
<?php

require_once 'db-if.php';
require_once 'user.php';

$user = new User;
$user->name = 'John';
$user->save();

モデル定義とサンプルコードはチュートリアルそのままですが、これで書き込みができるはず。
確認してみましょう。


# mongo
> show dbs;
admin   0.000GB
config  0.000GB
db      0.000GB
local   0.000GB
> use db;
switched to db db
> show collections;
users_collection
> db.users_collection.find();
{ "_id" : ObjectId("5ccde0599dc6d668860b1292"), "name" : "John", "updated_at" : ISODate("2019-05-04T18:56:25Z"), "created_at" : ISODate("2019-05-04T18:56:25Z") }

できてますね。
では、次はデータをphpから取得します。

read-test.php
<?php

require_once 'mongoif.php';
require_once 'user.php';

$users = User::all();
foreach($users as $user) {
    var_dump($user->name);
}

実行しましょう。


# php read-test.php
string(4) "John"

無事に取得できました。

NoSQLであるmongodbをEloquentで扱えればAPIサーバーを作成するのも大分楽になるのでは、と思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?