terales / yesql-php

A clone of the wonderful yesql clojure library, for php

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

yesql-php Build Status

I'm trying to build a clone of the wonderful yesql library from clojure. The idea is to have a seperate sql file for queries, which you can then access as methods on a class.

Installation

Use composer to require:

"nulpunkt/yesql-php": "^1"

Examples!

You need to make a repository of queries:

$pdo = new PDO($host, $user, $pass); // Fill in the blanks
$r = new Nulpunkt\Yesql\Repository($pdo, "my-queries/queries.sql");

in queries.sql we can put:

-- name: getAllRows
-- This will fetch all rows from test_table
select * from test_table;

which will allow us to call

$r->getAllRows();

A database without rows is not of much use, lets insert some data:

-- name: insertRow
insert into test_table (something) values (?)
// returns the insertId
$r->insertRow('a thing');

As default, yesql will simply bind all params passed to the called function, to the query associated with it. We'll see how to make mappers further down.

Maybe we need to fix some exsisting data

-- name: updateRow
update test_table set something = ? where id = ?
// returns the number of rows touched by the update
$r->updateRow('fixed thing', 3);

yesql-php support different modlines, lets say we know we only need to get one row:

-- name: getById oneOrMany: one
select * from test_table where id = ?;
// Fetches one row with id 3
$r->getById(3);

Maybe we want to return a modified version of the row. By specifying a rowFunc, we can have a function called, on every row returned:

-- name: getMappedById oneOrMany: one rowFunc: MyObject::mapRow
select * from test_table where 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);

Sometimes an object is want you want, rowClass got your back:

-- name: getObjectById oneOrMany: one rowClass: MyObject
select * from test_table where id = ?
class MyObject {
}
// return one row, which is an instance of MyObject with id and something set
$r->getObjectById(3);

Maybe we have a class with a toRow method we'd like to call on insert

-- 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) 

About

A clone of the wonderful yesql clojure library, for php


Languages

Language:PHP 98.6%Language:Shell 1.4%