yannickforest/mongodm

MongoDB ORM,支持引用、嵌入和多级继承。

1.4.2 2014-07-31 10:22 UTC

This package is not auto-updated.

Last update: 2024-09-23 13:52:26 UTC


README

SensioLabsInsight Build Status Latest Stable Version Total Downloads License

简介

Mongodm是一个MongoDB ORM,支持引用、嵌入甚至多级继承。

功能

  • ORM
  • 简单灵活
  • 支持嵌入
  • 支持引用(懒加载)
  • 支持多级继承
  • 支持本地集合操作

需求

  • PHP 5.3或更高版本
  • Mongodb 1.3或更高版本
  • PHP Mongo扩展

安装

1. 在composer.json中设置

	{
		"require": {
		    "purekid/mongodm": "dev-master"
		}
	}

2. 使用composer安装

$ php composer.phar update

数据库设置

数据库配置文件(默认位置为/vendor/purekid/mongodm/config.php)

	return array(
        'default' => array(
    		'connection' => array(
    			'hostnames' => 'localhost',
    			'database'  => 'default',
    // 			'username'  => '',
    // 			'password'  => '',
    		)
    	),
    	'production' => array(
    		'connection' => array(
    			'hostnames' => 'localhost',
    			'database'  => 'production',
    			'options' => array('replicaSet' => 'rs0')
    		)
    	)
    );

认证

认证信息通过选项数组传递。如果您未指定authSource,则PHP Mongo驱动程序将选择"admin"数据库。

$config =  array( 'connection' => array(
      'hostnames' => '<host>:<port>',
      'database'  => '<databasename>',
      'options'  => [ "connectTimeoutMS" => 500 , "username" => "admin", "password" => "<password>", "authSource" => "admin"] )
  );

在应用程序中设置数据库

1. 您可以使用MongoDB::setConfigBlock方法设置配置。

\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()
    )
));

2. 或者,您可以将配置文件复制到项目中,然后在其中定义一个全局常量'MONGODM_CONFIG'以及其位置。

//in a global initialization place

define('MONGODM_CONFIG',__DIR__."/../config/mongodm.php");

根据APPLICATION_ENV选择配置部分

Mongodm使用哪个配置部分?Mongodm默认选择'default'部分。

您有两种方式来指定部分

1. 模型中的'$config'属性,您可以在下面的示例中找到此属性。

2. 使用环境常量'APPLICATION_ENV',此常量可以通过web服务器、您的代码或shell环境设置。在这种情况下,您应设置$config='default'或不在自己的模型类中声明$config。

创建一个模型并享受它

    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'
	]

如果您将对象实例放入模型属性中,并且该属性在模型类的$attrs中未定义,则在模型保存时将省略该属性的数据。

    
    $object = new \stdClass();  
    $object->name = 'ooobject';
    
    $user = new User();
    $user->name = 'michael';
    $user->myobject = $object;    // this attribute will be omitted when saving to DB 
    $user->save();

模型CRUD

创建

	$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

设置和获取值

您可以通过变量$user->name = "John"或通过方法$user->getName()来设置/获取值。

使用变量或方法设置

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

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

使用变量或方法获取

 	// "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"

更新

	$user->age = 19;

通过数组更新属性

	$user->update( array('age'=>18,'hobbies'=>array('music','game') ) ); 
	$user->save();

取消设置属性

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

检索单条记录

	$user = User::one( array('name'=>"michael" ) );

通过MongoId检索单条记录

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

检索记录

检索名称为'Michael'且拥有书籍账户等于2的记录

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

检索所有记录

	$users = User::all();

计数记录

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

删除记录

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

关系 - 引用

懒加载1:1关系记录

	$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;

懒加载1:n关系记录

	$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;     

集合

$users是集合的实例

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

保存

    $users->save() ;  // foreach($users as $user) { $user->save(); }

删除

    $users->delete() ;  // foreach($users as $user) { $user->delete(); }

计数

	$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();

切片和取

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

映射

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

过滤

	$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();

检索和检查值

	$bob = Student::one( array("name"=>"Bob") );
	
	echo $bob->dad->name;    // David
	
	$classmates = $bob->classmates;
	
	echo $classmates->count(); // 2
    
	var_dump($classmates->get(0)); // john	

检索子类

检索所有人类记录,由于它是一个顶级类,查询时不包含 '_type'。

    $humans = Human::all();

检索所有学生记录,由于它是一个子类,查询时包含 { "_type":"Student" }。

    $students = Student::all();

检索不包含 _type

为了检索不包含 _type 条件(即 { "_type":"Student" })的记录

class Student extends \Purekid\Mongodm\Model
{
    protected static $useType = false;

    protected static $collection = 'Student';
}

请确保设置一个集合,否则您将获得包含每个 _type 的结果。

模型中的其他静态方法

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

模型钩子

以下钩子可用

__init__()

在构造函数完成后执行

__preInsert__()

在保存新记录之前执行

__postInsert__()

在保存新记录后执行

__preUpdate__()

在保存现有记录之前执行

__postUpdate__()

在保存现有记录后执行

__preSave__()

在保存记录之前执行

__postSave__()

在保存记录后执行

__preDelete__()

在删除记录之前执行

__postDelete__()

在删除记录后执行

特别感谢

mikelbring Paul Hrimiuc