Mongodm : 一个PHP的mongo ORM 操作组件

12 篇文章 0 订阅

PHP提供的一系列的Mongo操作类已经很强大了. 但是仍然不是很友好.这在以前使用的时候就有感触, 当时是自己团队写的一套封装, 也经常出现种种的问题.

目前在用Phalcon, 框架还在发展阶段, 只提供了cache类操作. 

在github和mongodb官网上寻找成熟的优秀的组件, 找到不少, 琳琅满目, 新旧不一, 我从中找了一个说明文档详细,更新及时,维护完善的项目: Mongodm.


特点

orm   

简单,灵活  

支持嵌入  

支持引用

支持多级继承  

支持本地收集操作


数据库配置

return array(
        'default' => array(
            'connection' => array(
                'hostnames' => 'localhost',
                'database'  => 'default',
    //          'username'  => '',
    //          'password'  => '',
            )
        ),
        'production' => array(
            'connection' => array(
                'hostnames' => 'localhost',
                'database'  => 'production',
                'options' => array('replicaSet' => 'rs0')
            )
        )
    );
或者使用内置方法配置:

\Purekid\Mongodm\MongoDB::setConfigBlock('default', array(
    'connection' => array(
        'hostnames' => 'localhost',
        'database'  => 'default',
        'options'  => array()
    )
));

// 
\Purekid\Mongodm\MongoDB::setConfigBlock('auth', array(
    'connection' => array(
        'hostnames' => 'localhost',
        'database'  => 'authDB',
        'options'  => array()
    )
));

创建模型:

class User extends \Purekid\Mongodm\Model 
    {

        static $collection = "user";

        /** use specific config section **/
        public static $config = 'testing';

        /** specific definition for attributes, not necessary! **/
        protected static $attrs = array(

             // 1 to 1 reference
            'book_fav' => array('model'=>'Purekid\Mongodm\Test\Model\Book','type'=>'reference'),
             // 1 to many references
            'books' => array('model'=>'Purekid\Mongodm\Test\Model\Book','type'=>'references'),
            // you can define default value for attribute
            'age' => array('default'=>16,'type'=>'integer'),
            'money' => array('default'=>20.0,'type'=>'double'),
            'hobbies' => array('default'=>array('love'),'type'=>'array'),
            'born_time' => array('type'=>'timestamp'),
            'family'=>array('type'=>'object'),
            'pet_fav' => array('model'=>'Purekid\Mongodm\Test\Model\Pet','type'=>'embed'),
            'pets' => array('model'=>'Purekid\Mongodm\Test\Model\Pet','type'=>'embeds'),

        );

        public function setFirstName($name) {
            $name = ucfirst(strtolower($name));
            $this->__setter('firstName', $name);
        }

        public function getLastName($name) {
            $name = $this->__getter('name');
            return strtoupper($name);
        }

    }
模型属性:

$types = [
        'mixed',  // mixed type 
        'string',     
        'reference',  // 1 : 1 reference
        'references', // 1 : many references
        'embed', 
        'embeds', 
        'integer',  
        'int',  // alias of 'integer'
        'double',     // float 
        'timestamp',  // store as MongoTimestamp in Mongodb
        'date',  // store as DateTime
        'boolean',    // true or false
        'array',    
        'object'
    ]

创建(Create)

    $user = new User();
    $user->name = "Michael";
    $user->age = 18;
    $user->save();
带初始值:

    $user = new User( array('name'=>"John") );
    $user->age = 20;
    $user->save();
使用赋值的方式:

    $user->setLastName('Jones'); // Alias of $user->lastName = 'Jones';
    $user->setFirstName('John'); // Implements setFirstName() method

可以set/get value 通过属性: $user->name = "kevin" 或者通过方法: $user->getName().

    // SET: 
    // no "set" method exists
    $user->lastName = 'Jones';
    $user->setLastName('Jones');

    // "set" method exists implements setFirstName()
    $user->firstName = 'jOhn'; // "John"
    $user->setFirstName('jOhn'); // "John"

    // =========

    // GET:
    // "get" method exists implements getLastName()
    print $user->lastName; // "JONES"
    print $user->getLastName(); // "JONES"

    // no "get" method
    print $user->firstName; // "John"
    print $user->setFirstName('John'); // "John"

更新(Update)

$user->age = 19;
更新数组:

    $user->update( array('age'=>18,'hobbies'=>array('music','game') ) ); 
    $user->save();
释放(unset)属性:

    $user->unset('age');
    $user->unset( array('age','hobbies') )

检索一条记录

    $user = User::one( array('name'=>"michael" ) );
通过Id检索一条记录:

    $id = "517c850641da6da0ab000004";
    $id = new \MongoId('517c850641da6da0ab000004'); //another way
    $user = User::id( $id );

检索多条记录

    $params = array( 'name'=>'Michael','books'=>array('$size'=>2) );
    $users = User::find($params);     // $users is instance of Collection
    echo $users->count();

检索所有记录

    $users = User::all();

统计记录(COUNT)

    $count = User::count(array('age'=>16));

删除记录

    $user = User::one();
    $user->delete();    



实例参考 -- 关系

一对一关系:

    $book = new Book();
    $book->name = "My Love";
    $book->price = 15;
    $book->save();

    // !!!remember you must save book before!!!
    $user->book_fav = $book;
    $user->save();

    // now you can do this
    $user = User::one( array('name'=>"michael" ) );
    echo $user->book_fav->name;
一对多关系:

    $user = User::one();
    $id = $user->getId();

    $book1 = new Book();
    $book1->name = "book1";
    $book1->save();

    $book2 = new Book();
    $book2->name = "book2";
    $book2->save();

    $user->books = array($book1,$book2);
    //also you can
    $user->books = Collection::make(array($book1,$book2));
    $user->save();

    //somewhere , load these books
    $user = User::id($id);
    $books = $user->books;      // $books is a instance of Collection

实例参考 -- 内嵌

单一嵌入:

    $pet = new Pet();
    $pet->name = "putty";

    $user->pet_fav = $pet;
    $user->save();

    // now you can do this
    $user = User::one( array('name'=>"michael" ) );
    echo $user->pet_fav->name;


嵌入集合:

    $user = User::one();
    $id = $user->getId();

    $pet_dog = new Pet();
    $pet_dog->name = "puppy";
    $pet_dog->save();

    $pet_cat = new Pet();
    $pet_cat->name = "kitty";
    $pet_cat->save();

    $user->pets = array($pet_cat,$pet_dog);
    //also you can
    $user->pets = Collection::make(array($pet_cat,$pet_dog));
    $user->save();

    $user = User::id($id);
    $pets = $user->pets;     


收集器:

下面$user是收集的实例:

    $users = User::find(  array( 'name'=>'Michael','books'=>array('$size'=>2) ) );    
    $users_other = User::find(  array( 'name'=>'John','books'=>array('$size'=>2) ) );   
count:

    $users->count();  
    $users->isEmpty();
迭代:
    foreach($users as $user) { }  
      // OR use Closure 
      $users->each(function($user){
    })
排序:

    //sort by age desc
    $users->sortBy(function($user){
        return $user->age;
    });

    //sort by name asc
    $users->sortBy(function($user){
        return $user->name;
    } , true);

    //reverse collection items
    $users->reverse();

Slice and Take:

    $users->slice(0,1);
    $users->take(2);
Map:

    $func = function($user){
                if( $user->age >= 18 ){
                    $user->is_adult = true;
                    return $user;
                }
            };

    $adults = $users->map($func);   

    // Notice:  1. $adults is a new collection   2. In original $users , data has changed at the same time.
Filter:

    $func = function($user){
                if( $user->age >= 18 ){
                    return true;
                }
            }

    $adults = $users->filter($func); // $adults is a new collection
确保集合中的一条记录存在于实例中:

    $john = User::one(array("name"=>"John"));

    $users->has($john) 
确保集合中的记录存在数字索引:
    $users->has(0) 
确保记录存在MONGOID:

$users->has('518c6a242d12d3db0c000007') 
通过数字索引获得一条记录:

    $users->get(0) 
通过MONGOID获得一条记录:

    $users->get('518c6a242d12d3db0c000007') 
通过数字索引删除一条记录:

    $users->remove(0)  
通过MONGOID删除一条记录:

    $users->remove('518c6a242d12d3db0c000007') 
添加一条记录到收集器中:

    $bob = new User( array("name"=>"Bob"));
    $bob->save();
    $users->add($bob);
添加多条记录到收集器中:

    $bob = new User( array("name"=>"Bob"));
    $bob->save();
    $lisa = new User( array("name"=>"Lisa"));
    $lisa->save();

    $users->add( array($bob,$lisa) ); 
合并两个收集器:

    $users->add($users_other);  // the collection $users_other appends to end of $users 
导出数据到一个数组:

    $users->toArray();

继承

定义多级继承类:

    use Purekid\Mongodm\Model;
    namespace Demo;

    class Human extends Model{

        static $collection = "human";

        protected static $attrs = array(
            'name' => array('default'=>'anonym','type'=>'string'),
            'age' => array('type'=>'integer'),
            'gender' => array('type'=>'string'),
            'dad' =>  array('type'=>'reference','model'=>'Demo\Human'),
            'mum' =>  array('type'=>'reference','model'=>'Demo\Human'),
            'friends' => array('type'=>'references','model'=>'Demo\Human'),
        )

    }

    class Student extends Human{

        protected static $attrs = array(
            'grade' => array('type'=>'string'),
            'classmates' => array('type'=>'references','model'=>'Demo\Student'),
        )

    }


使用:

    $bob = new Student( array('name'=>'Bob','age'=> 17 ,'gender'=>'male' ) );
    $bob->save();

    $john = new Student( array('name'=>'John','age'=> 16 ,'gender'=>'male' ) );
    $john->save();

    $lily = new Student( array('name'=>'Lily','age'=> 16 ,'gender'=>'female' ) );
    $lily->save();

    $lisa = new Human( array('name'=>'Lisa','age'=>41 ,'gender'=>'female' ) );
    $lisa->save();

    $david = new Human( array('name'=>'David','age'=>42 ,'gender'=>'male') );
    $david->save();

    $bob->dad = $david;
    $bob->mum = $lisa;
    $bob->classmates = array( $john, $lily );
    $bob->save();

检索并检查value:

    $bob = Student::one( array("name"=>"Bob") );

    echo $bob->dad->name;    // David

    $classmates = $bob->classmates;

    echo $classmates->count(); // 2

    var_dump($classmates->get(0)); // john  


获取子类:

获取所有Humans record , 查询不用_type, 因为他是一个顶级类:

    $humans = Human::all();
获取所有Student records , 查询是i用 { "_type":"Student" } , 因为他是一个子类:

    $students = Student::all();

查询子类不用_type:
To retrieve a record without the _type criteria (i.e. { "_type":"Student" }) set:
class Student extends \Purekid\Mongodm\Model
{
    protected static $useType = false;


    protected static $collection = 'Student';
}
Make sure to set a collection otherwise you will get results with every _type.


其他的模型静态方法

    User::drop() // Drop collection 
    User::ensureIndex()  // Add index for collection

模型钩子

The following hooks are available:

__init()

Executed after the constructor has finished

__preInsert()

Executed before saving a new record

__postInsert()

Executed after saving a new record

__preUpdate()

Executed before saving an existing record

__postUpdate()

Executed after saving an existing record

__preSave()

Executed before saving a record

__postSave()

Executed after saving a record

__preDelete()

Executed before deleting a record

__postDelete()

Executed after deleting a record



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值