承接 somnambulist/read-models 相关项目开发

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

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

somnambulist/read-models

最新稳定版本:4.1.1

Composer 安装命令:

composer require somnambulist/read-models

包简介

A stripped down active-record'ish query layer for fetching data from your database.

README 文档

README

GitHub Actions Build Status Issues License PHP Version Current Version

Read-Models are a companion resource to a Doctrine ORM entity based project. They provide an active-record style data access layer, designed for presentational purposes only. This allows your domain objects to remain completely focused on managing your data and not getting sidelined with presentational concerns.

To further highlight this tight integration, read-models uses DBAL and the DBAL type system under-the-hood. Any registered types will be used during model hydration and even embeddables can be reused.

Note that unlike standard active-record packages, there is no write support at all nor will this be added. This package is purely focused on reading and querying data with objects / query builders for use in the presentation layer.

A lot of the internal arrangement is heavily inspired by Laravels Eloquent and other active-record projects including GranadaORM (IdiORM), PHP ActiveRecord and others.

Supported Features

  • active-record query model
  • read-only - no ability to change your db through the built-in methods
  • read-only models - no mutation methods, models are immutable once loaded
  • support for attribute casting
  • support for embedded objects via attribute casting
  • support for exporting as JSON / Array data (configurable)
  • eager loading of relationships including batch loading
  • relationships (1:1, 1:m, m:m, 1:m reversed)
  • identity map
  • pluggable attribute casting / cast to value-objects

Requirements

  • PHP 8.1+
  • mb_string
  • doctrine/dbal
  • somnambulist/collection

Installation

Install using composer, or checkout / pull the files from github.com.

  • composer require somnambulist/read-models
  • instantiate Manager with your connection mappings and any attribute casters
  • add models extending the Model class, being sure to set the table name property
  • load some data: <model>::find()

For example:

use Doctrine\DBAL\DriverManager;
use Somnambulist\Components\ReadModels\Manager;
use Somnambulist\Components\ReadModels\TypeCasters\DoctrineTypeCaster;

new Manager(
[
    User::class => $conn = DriverManager::getConnection(['url' => 'sqlite://db.sqlite']),
    'default'   => $conn,
],
[
    new DoctrineTypeCaster($conn),
]
);

Usage

Extend Somnambulist\Components\ReadModels\Model and add casts, define relationships, exports etc.

class User extends Model
{
    protected string $table = 'users';
}

You can add a default table alias by setting the property: $tableAlias. Other defaults can be overridden by defining the property:

class User extends Model
{
    protected string $table = 'tbl_users';
    protected ?string $tableAlias = 'u';
    protected string $primaryKey = 'uuid';
}

Note: properties are defined with types and must follow those defined in the base class.

To load a record:

$model = User::find(1);

$results = User::query()->whereColumn('name', 'like', '%bob%')->orderBy('created_at', 'desc')->limit(5)->fetch();

Access properties directly or via method calls:

$model = User::find(1);

$model->id;
$model->id();
$model->created_at;
$model->createdAt();

You cannot set, unset, or change the returned models.

You can define attribute mutators in the same way as Laravels Eloquent:

class User extends Model
{
    protected function getUsernameAttribute($username)
    {
        return Str::capitalize($username);
    }
}

// user:{username: bob was here} -> returns Bob Was Here

User::find(1)->username();

Note: these methods should be protected as they expect the current value to be passed from the loaded model attributes.

Or create virtual properties, that exist at run time:

class User extends Model
{
    protected function getAnniversayDayAttribute()
    {
        return $this->created_at->format('l');
    }
}

// user:{created_at: '2019-07-15 14:23:21'} -> "Monday"

User::find(1)->anniversay_day;
User::find(1)->anniversayDay();

Or for micro-optimizations, add the method directly:

class User extends Model
{
    public function anniversayDay()
    {
        return $this->created_at->format('l');
    }
}

// user:{created_at: '2019-07-15 14:23:21'} -> "Monday"

User::find(1)->anniversayDay();

Note: to access properties via the magic __get/call the property name must be a valid PHP property/method name. Keys that start with numbers (for example), will not work. Any virtual methods / properties should be documented using @property-read tags on the class level docblock comment. Additionally: virtual methods can be tagged using @method.

Note: to get a raw attribute value, use ->getRawAttribute(). This will return null if the attribute is not found, but could also return null for the specified key.

When returning sets of Model objects, the returned set can be customised per model to allow for specific filters on the collection or other behaviour. Override the collectionClass property with the class name to use. This class must implement the Collection contract from the somnambulist/collection project and must have extract() and add() methods.

More Reading

Auto-generated API docs are available in the docs folder.

Profiling

If you use Symfony; using the standard Doctrine DBAL connection from your entity manager will automatically ensure that ALL SQL queries are added to the profiler without having to do anything else! You get full insight into the query that was executed, the data bound etc. For further insights consider using an application profiler such as:

For other frameworks; as DBAL is used, hook into the Configuration object and add an SQL logger instance that can report to your frameworks profiler.

Test Suite

The test suite uses an SQlite database file named "users.db" that simulates a possible User setup with Roles, Permissions, Contacts and Addresses. Before running the test suite, be sure to generate some test data using: tests/resources/seed.php. This console app has a couple of commands:

  • db:create - builds the table structure
  • db:seed - generate base records and --records=XX random records
  • db:destroy - deletes all test data and tables

For the test suite to run and be able to test various relationships / eager loading etc a reasonable number of test records are needed. The suite was built against a random sample of 150 records.

The DataGenerator attempts some amount of random allocation of addresses, contacts and roles to each user; however data integrity was not the goal, merely usable data.

To run the tests: vendor/bin/phpunit.

somnambulist/read-models 适用场景与选型建议

somnambulist/read-models 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3.21k 次下载、GitHub Stars 达 12, 最近一次更新时间为 2019 年 07 月 05 日, 在 PHP 生态内属于活跃度较高的组件。

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

围绕 somnambulist/read-models 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 3.21k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 12
  • 点击次数: 8
  • 依赖项目数: 3
  • 推荐数: 0

GitHub 信息

  • Stars: 12
  • Watchers: 5
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-07-05