nulpunkt / yesql-php
优秀的yesql clojure库的PHP克隆版本
v1.5.0
2022-05-17 08:24 UTC
Requires (Dev)
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: 3.*
README
这是clojure的yesql库的克隆版本。想法是有一个独立的SQL文件用于查询,然后你可以将它们作为类的方法来访问。
我在周五为了娱乐而构建了这个项目,非常喜欢它,现在我们在工作中也在使用它。所以我认为它已经可以用于生产环境了。
安装
使用composer来require
"nulpunkt/yesql-php": "^1"
示例!
你需要创建一个查询的仓库
$pdo = new PDO($host, $user, $pass); // Fill in the blanks $r = new Nulpunkt\Yesql\Repository($pdo, "my-queries/queries.sql");
获取多行
在queries.sql
中我们可以放入
-- name: getAllRows -- This will fetch all rows from test_table select * from test_table;
这将允许我们调用
$r->getAllRows();
插入一行
一个没有行的数据库没有什么用处,让我们插入一些数据
-- name: insertRow(thing) insert into test_table (something) values (:thing)
// returns the insertId $r->insertRow('a thing');
默认情况下,yesql将简单地绑定传递给调用函数的所有参数到相关的查询。我们将在下面看到如何进行映射。
更新一行
可能我们需要修复一些现有的数据
-- name: updateRow(id, thing) update test_table set something = :thing where id = :id
// returns the number of rows touched by the update $r->updateRow(3, 'fixed thing');
获取单行
yesql-php支持不同的modlines,假设我们只知道我们只需要获取一行
-- name: getById(id) oneOrMany: one select * from test_table where id = :id;
// Fetches one row with id 3 $r->getById(3);
一次性获取和映射行
可能我们想返回行的修改版本。通过指定rowFunc,我们可以在返回的每一行上调用一个函数
-- name: getMappedById(id) oneOrMany: one rowFunc: MyObject::mapRow select * from test_table where id = :id
class MyObject { public static function mapRow($r) { return ['id' => $r['id'], 'ohwow' => $r['something']]; } } // return one row, with keys id and ohwow $r->getMappedById(3);
将行映射到对象
有时需要一个对象,rowClass可以帮到你
-- name: getObjectById(id) oneOrMany: one rowClass: MyObject select * from test_table where id = :id
class MyObject { } // return one row, which is an instance of MyObject with id and something set $r->getObjectById(3);
在传入过程中映射数据
我们可能需要映射我们的领域对象,以便将它们插入数据库。
-- name: insertObject inFunc: MyObject::toRow insert into test_table (id, something) values (:id, :something)
class MyObject { // $i will be the arguments passed to insertObject public static function toRow($i, $o) { return ['id' => $i, 'something' => $o->something]; } } $o = new MyObject; $r->insertObject($i, $o)