martynbiz / database
数据库类集合,允许数据库操作和单元测试
dev-master
2014-11-30 11:43 UTC
Requires
- php: >=5.3.0
Requires (Dev)
- phpunit/phpunit: 4.3.*
This package is not auto-updated.
Last update: 2024-09-24 08:27:58 UTC
README
#数据库
轻量级 ORM 类。它旨在非常适合单元测试,其中数据库适配器可以轻松模拟。同时也提供了足够的工具来完成常见的任务,如查找/选择/创建/更新/删除,以及表之间的关系(例如 hasMany/ belongsTo)。可以独立运行或在框架内运行。
##安装
使用 composer 安装
"martynbiz/database": "dev-master"
##ORM
Models/User.php
class User extends MartynBiz\Database\Table { protected $table = 'users'; }
脚本
$adapter = new MartynBiz\Database\Adapter(array( 'dsn' => '...', 'user' => '...', 'password' => '...', )); $usersTable = Users::getInstance($adapter); // return Row object $user = $usersTable->find($id); // select many rows by query (with options) $where = 'age > 34'; $options = array( 'limitStart' => 10, 'limitMax' => 25, ); $users = $usersTable->select($where, $options); // insert new row $values = array( 'name' => 'Hugo', 'age' => 54, ); $users->create($values); // update rows $usersTable->update($values, $where, $options); // delete rows $usersTable->delete($where, $options);
###关联
class User extends Table { protected $tableName = 'users'; protected $hasMany = array( 'transactions' => array( 'table' => 'App\Model\Transaction', // class name for the hasMany rows 'foreign_key' => 'user_id', ) ); } class Transaction extends Table { protected $tableName = 'transactions'; protected $belongsTo = array( 'user' => array( 'table' => 'App\Model\User', // class name for the belongsTo row 'foreign_key' => 'user_id', ) ); }
##数据库适配器
...
##单元测试
###表
$adapterMock = $this->getMockBuilder('MartynBiz\Database\Adapter') ->disableOriginalConstructor() ->getMock(); $usersTable = new Users($adapterMock);
###适配器
如果需要扩展适配器类,通常内部生成的 PDO 对象可以注入代替(数据库凭据将被忽略)。这允许扩展类使用模拟的 PDO 对象进行单元测试。
class MyCustomAdapter extands Adapter { } $PDOMock->expects( $this->once() ) ->method('prepare') ->with($sql); $PDOStatementMock->expects( $this->once() ) ->method('execute') ->with($whereValues); $PDOStatementMock->expects( $this->once() ) ->method('fetchAll') ->will( $this->returnValue($mockExecuteResult) ); // create instance with mock $adapter = new MyCustomAdapter(null, $PDOMock);
待办事项
- 级联