1. Go to this page and download the library: Download swew/db library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
swew / db example snippets
use Swew\Db\ModelConfig;
// PDO connection init
ModelConfig::init($dsn, $username, $password);
use Swew\Db\{Migrate,ModelConfig};
// path to autoload file
sqlite');
ModelConfig::setPDO($pdo);
// "**" - is alias for sub folders
$filePattern = __DIR__ . '/migrations/**.php';
// Run "UP" migrations
$isUpMigration = true;
Migrate::run($filePattern, $isUpMigration);
use Swew\Db\Model;
class UserModel extends Model {
// acceptable fields, should be used with default values, so there are no errors in php 8.2
public ?int $id = null;
public string $login = '';
public string $name = '';
public string $password = '';
public int $rating = 0;
// Table name [al] [default: false]
protected function hasTimestamp(): bool {
return true;
}
protected function cast(): array {
return [
'to' => [
'password' => fn ($str) => password_hash($str, PASSWORD_BCRYPT),
],
'from' => [
'created_at' => fn(int|string|null $timeStamp) => $timeStamp ? date('Y.m.d - H:i:s', (int)$timeStamp) : '',
'updated_at' => fn(int|string|null $timeStamp) => $timeStamp ? date('Y.m.d - H:i:s', (int)$timeStamp) : '',
],
];
}
protected function mapTable(): array
{
return [
// 'TABLE' => $this, // default value, fixed
'T1' => $this,
'T2' => CommentModel::class,
'T3' => 'table_name',
];
}
// SQL Query
const MOST_POPULAR_USER = 'SELECT id, login, name FROM [TABLE] WHERE rating >= 9';
const FIND_BY_NAME = 'SELECT id, login, name FROM [TABLE] WHERE name = ?';
const UPDATE_NAME_BY_ID = 'UPDATE [TABLE] SET name = ? WHERE id = ?';
const UPDATE_NAME = 'UPDATE [TABLE] SET name = ?';
const INSERT_LOGIN_NAME = 'INSERT INTO [TABLE] (login, name) VALUES (:login, :name)';
const JOIN_COMMENT = 'SELECT [T1].name, [T2].comment FROM [T1] JOIN [T2] ON [T1].id=[T2].user_id';
}
// const MOST_POPULAR_USER = 'SELECT id, login, name FROM [TABLE] WHERE rating >= 9';
// const FIND_BY_NAME = 'SELECT id, login, name FROM [TABLE] WHERE name = ?';
UserModel::vm()->query(UserModel::FIND_BY_NAME, 'Jack')->get(); // array list
UserModel::vm()->query(UserModel::FIND_BY_NAME, 'Jack')->getFirst(); // array data with first item with limit
UserModel::vm()->query(UserModel::MOST_POPULAR_USER)->getFirst();
UserModel::vm()->query(UserModel::FIND_BY_NAME, 'Jack')->getFirstItem(); // UserModel
UserModel::vm()->query(UserModel::FIND_BY_NAME, 'Jack')->getItems(); // UserModel[]
UserModel::vm()->query(UserModel::MOST_POPULAR_USER)->getValue(); // First value from first item
// Mapped values
UserModel::vm()->query(UserModel::MOST_POPULAR_USER)->getMap(
fn ($v) => $v['login']
);