承接 piko/db-record 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

piko/db-record

Composer 安装命令:

composer require piko/db-record

包简介

A lightweight Active Record helper built on top of PDO.

README 文档

README

build Coverage Status

Piko Db Record is a lightweight Active Record implementation built on top of PDO.

It has been tested with:

  • SQLite
  • MySQL
  • PostgreSQL
  • MSSQL

Installation

It is recommended to install Piko Db Record with Composer:

composer require piko/db-record

Documentation

https://piko-framework.github.io/docs/db-record.html

Usage

First, ensure autoloading is available:

require 'vendor/autoload.php';

Define your model (attributes)

use Piko\DbRecord;
use Piko\DbRecord\Attribute\Table;
use Piko\DbRecord\Attribute\Column;

#[Table(name: 'contact')]
class Contact extends DbRecord
{
    #[Column(primaryKey: true)]
    public ?int $id = null;

    #[Column]
    public ?string $firstname = null;

    #[Column]
    public ?string $lastname = null;

    #[Column]
    public ?bool $active = false;
}

Optional: map DB columns to different PHP property names

use Piko\DbRecord;
use Piko\DbRecord\Attribute\Table;
use Piko\DbRecord\Attribute\Column;

#[Table(name: 'contact')]
class ContactMapped extends DbRecord
{
    #[Column(name: 'id', primaryKey: true)]
    public ?int $contactId = null;

    #[Column(name: 'firstname')]
    public ?string $firstName = null;

    #[Column(name: 'lastname')]
    public ?string $lastName = null;

    #[Column(name: 'active')]
    public ?bool $isActive = false;
}

You can then use either mapped property names ($contact->firstName) or underlying column names ($contact->firstname).

Optional: custom cast types (float, decimal, datetime_immutable, datetime_mutable, json)

use DateTimeImmutable;
use Piko\DbRecord;
use Piko\DbRecord\Attribute\Table;
use Piko\DbRecord\Attribute\Column;

#[Table(name: 'contact')]
class ContactAdvancedTypes extends DbRecord
{
    #[Column(primaryKey: true)]
    public ?int $id = null;

    #[Column(type: 'float')]
    public ?float $income = null;

    #[Column(name: 'name', type: 'json')]
    public ?array $nameData = null;

    #[Column(name: 'lastname', type: 'datetime_immutable')]
    public ?DateTimeImmutable $lastSeenAt = null;

    #[Column(name: 'firstname', type: 'decimal', scale: 4)]
    public ?string $balance = null;
}
  • float values are cast to PHP float.
  • decimal values are normalized as strings. With scale, values are rounded/formatted to that precision.
  • datetime_immutable values are cast to DateTimeImmutable.
  • datetime_mutable values are cast to DateTime.
  • json values are stored as JSON strings and exposed as PHP arrays.

datetime remains supported as an alias of datetime_immutable for backward compatibility.

Optional: legacy/manual schema (including string primary keys)

use Piko\DbRecord;

class ContactStringPk extends DbRecord
{
    protected string $tableName = 'contact';
    protected string $primaryKey = 'firstname';

    protected array $schema = [
        'firstname' => self::TYPE_STRING,
        'lastname'  => self::TYPE_STRING,
    ];
}

With non-integer primary keys, set the key before save() when creating a new row:

$contact = new ContactStringPk($db);
$contact->firstname = 'pk_insert';
$contact->lastname = 'Doe';
$contact->save(); // INSERT with provided primary key

Setup database connection

Create a PDO instance and initialize schema:

$db = new PDO('sqlite::memory:');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = <<<SQL
CREATE TABLE contact (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  firstname TEXT,
  lastname TEXT,
  active INTEGER DEFAULT 0
)
SQL;

$db->exec($query);

Recommended: always enable PDO::ATTR_ERRMODE = PDO::ERRMODE_EXCEPTION. DbRecord throws explicit contextual exceptions when SQL operations fail (PersistenceException for SQL execution, SchemaException for mapping/schema issues, RecordNotFoundException for missing rows). Exception mode still gives the clearest SQL diagnostics.

Perform CRUD operations

Create

Create a new record and save it to the database:

$contact = new Contact($db);
$contact->firstname = 'John';
$contact->lastname = 'Doe';
$contact->active = true;
$contact->save();

echo "Contact id: {$contact->id}"; // Contact id : 1

Read

$contact = (new Contact($db))->load(1);

var_dump($contact->firstname); // John

$exists = (new Contact($db))->exists(1); // true

Update

$contact->lastname = 'Doe Jr.';
$contact->save();

Delete

$contact->delete();

Known limitations

  • Composite primary keys are not supported.
  • save() updates all mapped columns (no dirty-field tracking yet).
  • For auto-increment integer primary keys, inserted IDs are filled from PDO::lastInsertId() when available.
  • For non-integer (e.g. string) primary keys, your application typically provides the key value.
  • save() performs an INSERT when the primary key is null or does not exist in database yet; otherwise it performs an UPDATE.

Running tests

Run full checks (all database targets + coding standards + static analysis):

composer tests

Run tests for one database only:

composer phpunit:sqlite
composer phpunit:mysql
composer phpunit:pgsql
composer phpunit:mssql

Support

If you encounter issues or have questions, feel free to open an issue on GitHub.

piko/db-record 适用场景与选型建议

piko/db-record 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 117 次下载、GitHub Stars 达 0, 最近一次更新时间为 2022 年 11 月 04 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「database」 「sql」 「Active Record」 「record」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 piko/db-record 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 piko/db-record 我们能提供哪些服务?
定制开发 / 二次开发

基于 piko/db-record 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 117
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 15
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: LGPL-3.0-or-later
  • 更新时间: 2022-11-04