Documentation MVC
Models and database
Models as plain classes and the db module: queries, inserts, updates, transactions.
Models
olala has no ORM and no base model class — and that's a deliberate choice. A model is an ordinary class in
site/models/ that knows how to fetch and save data. Thanks to autoloading
you don't need to include it manually: a use statement is enough.
<?php
namespace site\models;
use olala\modules\db;
use olala\modules\stringTools;
class Post {
public static function latest(int $limit = 10): array {
return db::getAllSQL(
'select * from blog.posts where published = true order by created_at desc limit :limit',
[':limit' => $limit]
);
}
public static function find(string $slug) {
return db::getRow('blog.posts', ['slug' => $slug]);
}
public static function create(string $title, string $text): int {
return db::insert('blog.posts', [
'title' => $title,
'text' => $text,
'slug' => stringTools::translit($title),
'created_at' => db::expression('now()'),
], 'id');
}
}use site\models\Post;
function indexAction() {
return $this->render('index', ['posts' => Post::latest()]);
}Connecting to the database
Connection parameters are set in config.php. The db module works through PDO and supports PostgreSQL and MySQL:
settings::set([
'db_adapter' => 'pgsql', // pgsql | mysql | nodb
'db_host' => '127.0.0.1',
'db_port' => '5432',
'db_name' => 'mysite',
'db_user' => 'mysite',
'db_pass' => 'secret',
]);
The connection is opened lazily — on the first call to db — and is then reused
until the end of the request. Pages that don't touch the database don't waste time connecting.
SQL errors are thrown as exceptions (PDO::ERRMODE_EXCEPTION).
The module was written primarily for PostgreSQL: insert() wraps column names in double quotes,
and returning the id is done via RETURNING. On MySQL, enable ANSI_QUOTES mode for insert()
or write inserts with getOneSQL() and get the id via db::lastInsertId().
Conditions
Most methods take a condition as an array ['column' => value]. Conditions are joined with AND,
and values are passed through prepared statements — SQL injection is ruled out.
db::getAll('shop.orders', ['user_id' => 7, 'status' => 'new']);
// select * from shop.orders where user_id=:user_id and status=:status
If you need something more complex than equality, pass the value as db::expression() —
in getAll() and delete() it is inserted into WHERE as is (the array key doesn't matter in that case):
db::getAll('shop.orders', [
'user_id' => 7,
'recent' => db::expression("created_at > now() - interval '7 days'"),
], 'order by created_at desc');The text of db::expression() goes into SQL unescaped. Never put user input into it.
Reading
| Method | Returns |
|---|---|
db::get($col, $table, $where, $suffix) | the value of one column of the first row, or null |
db::getRow($table, $where, $suffix) | the first row, or false |
db::getAll($table, $where, $suffix) | an array of rows |
db::getColumn($col, $table, $where) | a flat array of column values |
db::getOneSQL($sql, $vars) | a single value from arbitrary SQL |
db::getRowSQL($sql, $vars) | a single row from arbitrary SQL, or null |
db::getAllSQL($sql, $vars) | all rows from arbitrary SQL |
$suffix is the tail of the query: 'order by id desc limit 20'. Rows come back in PDO's default mode: fields can be accessed both by name and by index.
$title = db::get('title', 'blog.posts', ['id' => 5]);
$post = db::getRow('blog.posts', ['slug' => 'hello-world']);
$ids = db::getColumn('id', 'blog.posts', ['published' => true]);
$count = db::getOneSQL('select count(*) from blog.posts where author_id = :a', [':a' => 3]);
$rows = db::getAllSQL('select p.*, u.name from blog.posts p join site.users u on u.id = p.author_id');Writing
| Method | What it does |
|---|---|
db::insert($table, $data, $returning) | inserts a row; with $returning = 'id' it returns that column's value |
db::update($table, $data, $where) | updates rows matching the condition |
db::insertOrUpdate($table, $where, $data) | updates the row found by the condition, or inserts a new one (requires an id column) |
db::delete($table, $where) | deletes rows matching the condition |
db::lastInsertId($seq) | id of the last inserted row |
$id = db::insert('blog.posts', ['title' => 'Hello', 'slug' => 'hello'], 'id');
db::update('blog.posts', [
'views' => db::expression('views + 1'),
'updated_at' => db::expression('now()'),
], ['id' => $id]);
db::insertOrUpdate('site.settings', ['name' => 'theme'], ['value' => 'light']);
db::delete('blog.posts', ['id' => $id]);db::delete($table) without a condition deletes all rows in the table.
Transactions
db::beginTransaction();
try {
$orderId = db::insert('shop.orders', ['user_id' => $userId], 'id');
foreach ($cart as $item)
db::insert('shop.order_items', ['order_id' => $orderId] + $item);
db::commitTransaction();
} catch (\Exception $e) {
db::rollbackTransaction();
throw $e;
}For everything else the PDO object itself is available: db::getInstance()->pdo.
Migrations
A console command creates a migration stub — a file with a pair of functions returning the SQL to apply and roll back:
mkdir -p site/db/upgrades # once
./create db add_posts # → site/db/upgrades/db_up1790000000_add_posts.php<?php
function db_up1790000000_add_posts_up(){
return "create table blog.posts (id serial primary key, title text, slug text unique)";
};
function db_up1790000000_add_posts_down(){
return "drop table blog.posts";
};The command only creates the file: how and when to apply migrations is up to you — for example, with a small script that runs the _up() functions in file name order.
Service tables
Some framework modules store data in the database. If you use a module, create its table:
| Table | Used by | Columns |
|---|---|---|
site.logs | Log::error() and the core on errors | message, ip, type, crc, date |
site.sessions | Session in database storage mode | id, sid, ip, data, ping, user_id |
site.items | editable texts editable\text | id, owner, owner_id, data |
store.emails | background email sending | id, to, params, result, retrys, error, last_send_date |
stat.visitors | the visitors_stat.php console script | date, visitors |
An example for the error log in PostgreSQL:
create schema if not exists site;
create table site.logs (
id serial primary key,
date timestamp not null default now(),
message text,
ip varchar(45),
type int,
crc bigint
);