webcodr/mango

PHP的MongoDB对象文档映射器

0.6.13 2013-04-14 19:38 UTC

README

Build Status

PHP version

PHP的MongoDB对象文档映射器

Ruby的Mongoid启发

要求

  • PHP 5.4
  • PHP的MongoDB驱动程序(至少1.2.0版)
  • Composer

设置

将Mango添加到您的项目中

$ php composer.phar require webcodr/mango:*

创建文档类

<?php

namespace Mango\Tests\Document;

use Mango\Document;
use Mango\DocumentInterface;

class User implements DocumentInterface
{
    use Document;

    private function addFields()
    {
        $this->addField('name', ['type' => 'String']);
        $this->addField('email', ['type' => 'String']);

        $this->addField(
            'created_at',
            [
                'type' => 'DateTime',
                'index' => true,
                'default' => 'now'
            ]
        );

        $this->addField(
            'updated_at',
            [
                'type' => 'DateTime',
                'index' => true,
                'default' => 'now'
            ]
        );
    }
}

您无需设置集合名称。Mango使用小写类名作为集合名称。

如果您想设置自定义的集合名称,只需在您的文档类中重写getCollectionName()方法。

无需提供id。Mango的文档基类会自动添加包含新MongoId对象的属性'_id'。

保存文档

<?php

use Mango\Mango;
use Mango\DocumentManager;

use Document\User;

$mango = new Mango('mongodb://devserver:27017/galactica-actual');
$dm = new DocumentManager($mango);
$user = new User();
$user->name = 'William Adama';
$user->email 'william.adama@galactica.colonial-forces.gov';
$user->store();

删除文档

$user->remove();

查询

findwhere方法返回一个\Mango\Persistence\Cursor对象或\Collection\MutableMap类的对象。这取决于调用的是哪个方法。

MutableMap是另一个名为Collection的WebCodr项目的部分。它提供了一些类来替换PHP数组,并且使用起来更加有趣。请查看这里

Mango使用对象水合来自动提供文档对象的结果。

通过id查找文档
一个id
$user = User::find('abc')->first();
多个id
$user = User::find('abc', 'def', 'ghi')->first();
在集合中查找所有文档
User::where()->each(function($user) {
    echo $user->name;
});
查找具有特定字段值的文档
$user = User::where(['name' => 'William Adama']);
echo $user->count(); // result = 1
echo $user->first()->email; // result = william.adama@galactica.colonial-forces.gov