morris / dop
基于PDO的不可变API,用于组合和执行SQL语句
0.4.0
2020-05-09 15:14 UTC
Requires
- php: >=5.3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.14
- phpunit/phpunit: ^8
README
DOP是一个基于PDO的不可变API,用于组合和执行SQL语句。
- 扩展参数(
::param
和??
)允许将数组、null
和SQL片段等任意值绑定。 - 提供编写常见查询(例如选择、插入、更新、删除)的辅助工具。
- 已测试与SQLite、PostgreSQL和MySQL。
安装
DOP需要PHP >= 5.3.0和PDO。通过composer安装。
composer require morris/dop
用法
// Connect to a database $pdo = new PDO('sqlite:blog.sqlite3'); $dop = new Dop\Connection($pdo); // Find posts by author IDs using DOP parametrization $authorIds = [1, 2, 3]; $orderByTitle = $dop('ORDER BY title ASC'); $posts = $dop( 'SELECT * FROM post WHERE author_id IN (??) ??', [$authorIds, $orderByTitle] )->fetchAll(); // Find published posts using DOP helpers for common queries $posts = $dop->query('post')->where('is_published = ?', [1])->fetchAll(); // Get categorizations of posts using DOP's map function $categorizations = $dop( 'SELECT * FROM categorization WHERE post_id IN (??)', [$dop->map($posts, 'id')] )->fetchAll(); // Find posts with more than 3 categorizations using a sub-query as a parameter $catCount = $dop('SELECT COUNT(*) FROM categorization WHERE post_id = post.id'); $posts = $dop( 'SELECT * FROM post WHERE (::catCount) >= 3', ['catCount' => $catCount] )->fetchAll();
内部,在准备语句之前将??
和::named
参数解析。请注意,由于当前实现使用正则表达式,您应该永远不要直接使用引号字符串。始终使用绑定参数。
参考
请参阅API.md以获取完整的API参考。
贡献者
感谢!