crodas/easy-sql

史上最简单的SQL抽象

dev-master 2016-02-29 17:27 UTC

This package is auto-updated.

Last update: 2024-09-12 19:05:22 UTC


README

史上最简单的SQL抽象,深受yesql启发

概念

我整个职业生涯都在追求创建最简单的PHP SQL抽象。我多次放弃,直到我看到yesql的简洁。

重新发明SQL是一项繁琐的任务,往往徒劳无功。你需要放弃功能(使SQL独特之处)或性能(对于大多数Web应用来说难以想象)。

它是如何工作的?

EasySQL深受yesql的启发,这意味着你有一个包含SQL语句列表的单独文件,这些语句被编译成一个包含所有操作的PHP类。

-- This file is saved as queries/users.sql
-- @name byEmail
SELECT * FROM user WHERE email = $email LIMIT 1;

-- @name getContacts
SELECT 
  u.id, u.name, u.email 
FROM user 
INNER JOIN contacts c (c.friend_of = u.id)
WHERE c.user_id = $me;

-- @name create
INSERT INTO user(email) VALUES($email);

然后你需要以下PHP引导代码来运行它

$repo = new EasySQL\EasySQL("queries", $pdo);
$users = $repo->getRepository("users");

// find and return a single row due to the `LIMIT 1`. To force 
// a single row we can use @One annotation.
$me = $users->byEmail("crodas@php.net");

// All `INSERT` return the new created ID
$user_id = $users->create("crodas@php.net");

EasySQL的编译器将读取所有文件及其SQL语句,并生成一个包含所有查询和引导代码的PHP文件。