faslatam / orm
小型ORM,用于简单的CRUD操作。
v1.0.0
2023-11-09 07:47 UTC
Requires (Dev)
- phpunit/phpunit: ^10.4
This package is auto-updated.
Last update: 2024-09-09 09:53:19 UTC
README
小型ORM,用于基本的CRUD操作。
安装
通过Composer
$ composer require faslatam/orm
用法
模型
创建一个模型
任何模型都扩展了类 \Forestry\Orm\BaseModel
。
class User extends \Forestry\Orm\BaseModel { public static $database = 'example'; public static $table = 'users'; }
您必须定义数据库和表名。
使用模型
您可以定义所有表字段的getter和setter。
$user = new User; $user->setName('Bob'); $user->save();
getter/setter不是必须的。您可以直接访问属性
$user = new User; $user->name = 'Bob'; $user->save();
除了调用
save()
方法,您还可以显式调用insert()
或update()
。如果您在新的模型对象上设置了主键,您必须使用insert()方法。
连接
\Forestry\Orm\Storage
提供了一个PDO实例的注册表。
设置连接
连接是通过set()
方法定义的
\Forestry\Orm\Storage::set('default', [ 'dsn' => 'mysql:host=localhost', 'user' => 'root', 'password' => '', 'option' => [/* any PDO options can be defined here */] ]);
如果配置了,模型可以使用另一个连接
use \Forestry\Orm\Storage; use \Forestry\Orm\BaseModel; Storage::set('myOtherConnection', [ 'dsn' => 'mysql:host=127.0.0.1', 'user' => 'root', 'password' => '' ]); class Acme extends BaseModel { public static $storage = 'myOtherConnection'; public static $table = 'acme_table'; }
如果您尝试设置已定义的连接,
set()
将抛出LogicException
。
获取已定义的连接
您也可以像这样自由使用PDO连接
Storage::get('myOtherConnection')->exec('SELECT * FROM example.users');
如果您尝试获取未定义的连接,
get()
将抛出OutOfBoundsException
。
关闭连接
要关闭定义的连接,请使用delete()
方法
Storage::delete('myOtherConnection');
如果您尝试关闭未定义的连接,
delete()
将抛出OutOfBoundsException
。
测试
$ composer test
贡献
有关详细信息,请参阅CONTRIBUTING。
鸣谢
许可
MIT许可证(MIT)。有关更多信息,请参阅许可文件。