baddum / sql418
A library for extensible SQL requests
Requires
- php: >=5.4.0
README
SQL418
is a small PHP library for extensible SQL requests.
This library allows you to modify an existing SQL statement, by overriding some parts of it.
Features
Use the extend()
method to complete a request.
An example to add a WHERE
clause to a SELECT
request:
$request = new Baddum\SQL418\Request('SELECT * from table'); echo $request->extend('WHERE id = 39'); // SELECT * FROM table WHERE id = 39;
You can override a defined part of a request.
An example to change the selected fields:
echo $request->extend('SELECT name'); // SELECT name FROM table WHERE id = 39;
Use the &
keyword to extend a part of a request.
An example to add a field to select:
echo $request->extend('SELECT &, id'); // SELECT name, id FROM table WHERE id = 39;
You can change the type of a request.
An example to change a SELECT
request to a DELETE
one:
echo $request->extend('DELETE'); // DELETE FROM table WHERE id = 39;
You can also use all the features together:
$sql->extend('UPDATE SET name = "Albert" WHERE & AND right <> admin"'); echo $sql; // UPDATE table SET name = "Albert" WHERE id = 39 AND right <> admin;
Use cases
Use case: DRYer requests
In the following example, the fetchById
and deleteById
requests share a common pattern:
class UserModel { protected $SQLFetchById = 'SELECT * from user WHERE user.id=?'; protected $SQLDeleteById = ''; public function __construct() { $request = new Request($this->SQLFetchById); $this->SQLDeleteById = $request->extend('DELETE'); } }
Use case: extensible applications
In the following example, we extend the UserModel
to do a soft delete:
class UserModelSoftDelete extends UserModel { public function __construct() { $request = new Request($this->SQLFetchById); $this->SQLFetchById = $request->extend('WHERE & AND user.deleted = 0'); $this->SQLDeleteById = $request->extend('UPDATE & SET user.deleted = 1'); } }
How to Install
This library package requires PHP 5.4
or later.
Install Composer and run the following command to get the latest version:
composer require baddum/sql418:~1.2
How to Contribute
- Star the project!
- Tweet and blog about SQL418 and Let me know about it.
- Report a bug that you find
- Pull requests are highly appreciated. Please review the guidelines for contributing to go further.
Author & Community
SQL418 is under MIT License.
It was created & is maintained by Thomas ZILLIOX.