定制 pannella/laravel-cti 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

pannella/laravel-cti

Composer 安装命令:

composer require pannella/laravel-cti

包简介

A Laravel package for Class Table Inheritance support with automatic subtype casting.

README 文档

README

Tests Latest Stable Version License

A Laravel package for implementing the Class Table Inheritance (CTI) pattern with Eloquent models. Shared columns live in one parent table, type-specific columns live in their own tables, and a foreign key ties them together. The package handles type resolution, querying, and persistence automatically.

Features

  • Automatic model type resolution and instantiation
  • Seamless saving/updating across parent and subtype tables
  • Automatic batch-loading of subtype data (no N+1 queries)
  • Support for Eloquent events and relationships
  • Database-enforced referential integrity with real foreign keys

Requirements

  • PHP ^8.1
  • Laravel 8.x - 13.x (illuminate/database >=8.0 <14.0)

Installation

composer require pannella/laravel-cti

Quick Start

CTI uses three layers of tables: an optional lookup table for type definitions, a parent table for shared columns, and one or more subtype tables for type-specific columns.

// Parent table: shared attributes
Schema::create('assessments', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->foreignId('type_id')->constrained('assessment_types');
    $table->timestamps();
});

// Subtype table: quiz-specific attributes
Schema::create('assessment_quiz', function (Blueprint $table) {
    $table->unsignedBigInteger('assessment_id')->primary();
    $table->integer('passing_score')->nullable();
    $table->integer('time_limit')->nullable();
    $table->boolean('show_correct_answers')->default(false);

    $table->foreign('assessment_id')->references('id')->on('assessments')->onDelete('cascade');
});
// Parent model
class Assessment extends Model
{
    use HasSubtypes;

    protected static $subtypeMap = [
        'quiz' => Quiz::class,
        'survey' => Survey::class,
    ];

    protected static $subtypeKey = 'type_id';
    protected static $subtypeLookupTable = 'assessment_types';
    protected static $subtypeLookupKey = 'id';
    protected static $subtypeLookupLabel = 'label';

    protected $fillable = ['title', 'type_id'];
}

// Subtype model
class Quiz extends SubtypeModel
{
    protected $table = 'assessments'; // must be the parent table
    protected $subtypeTable = 'assessment_quiz';
    protected $subtypeAttributes = ['passing_score', 'time_limit', 'show_correct_answers'];
    protected $ctiParentClass = Assessment::class;

    protected $fillable = ['passing_score', 'time_limit', 'show_correct_answers'];
}
// Create
$quiz = Quiz::create([
    'title' => 'Final Exam',
    'passing_score' => 80,
    'time_limit' => 60,
]);

// Query (auto-joins subtype table when needed)
$hard = Quiz::where('passing_score', '>', 90)->get();

// Parent queries return correctly-typed subtype instances
$all = Assessment::all(); // mixed collection of Quiz, Survey, etc.

For the full setup guide including direct discriminator mode, PHP 8.1 attributes, and fillable/casts inheritance, see the Getting Started guide.

Documentation

  • Getting Started - Database schema, model setup, PHP attributes, fillable/casts inheritance
  • Configuration - Package configuration and missing subtype data handling
  • Querying - CRUD operations, query builder auto-joins, mass updates, supported methods
  • Relationships - Subtype relationships, foreign key behavior, parent relationship inheritance
  • Events - Subtype model events
  • Internals - Type resolution, caching, batch loading, save flow, known limitations
  • API Reference - Full method and property reference for all classes and traits

Why CTI?

If you have a type hierarchy in Laravel (for example, Quiz and Survey are both types of Assessment), there are a few common ways to model it. Each has tradeoffs.

Single Table Inheritance (STI)

One table holds every column for every type, with a discriminator column to distinguish them.

  • Pros: Simple queries, no joins, easy to set up.
  • Cons: You end up with a lot of nullable columns that don't apply to most rows, and the table gets wider every time you add a new type. This violates normalization: you're storing NULLs for columns that are structurally irrelevant to a given row, not just empty.

Separate Tables

Each type gets its own table (quizzes, surveys) with shared columns duplicated in each one.

  • Pros: Clean per-type schemas, no NULLs.
  • Cons: Shared columns are duplicated across tables. There's no unified way to query "all assessments." If you need to change a shared attribute, you have to update every table.

Polymorphic Relations

Laravel's morphTo/morphMany pattern stores a *_type and *_id pair so one entity can relate to multiple unrelated model types.

  • Pros: Flexible, built into Eloquent, and works well for its intended purpose (e.g., a Comment that can belong to either a Post or a Video).
  • Cons: Polymorphic relations are a relationship pattern, not an inheritance pattern. They solve "entity A relates to multiple unrelated entity types," not "entities A1 and A2 are specialized versions of entity A." Because the *_id column references different tables depending on the type value, you can't put a real foreign key constraint on it. Referential integrity is only enforceable in application code. Trying to use polymorphic relations to model a type hierarchy requires a lot of custom wiring and you lose the ability to query the parent type as a unified collection.

Class Table Inheritance (this package)

Shared attributes live in a parent table, type-specific attributes live in separate subtype tables linked by foreign key.

  • Pros: Properly normalized. No nullable columns, no duplicated columns, real foreign key constraints everywhere. You can query the parent type and get back a mixed collection of correctly-typed subtype instances. Subtype-specific queries auto-join as needed.
  • Cons: More tables to manage. Reads require joins (handled automatically by the package). Writes touch multiple tables (wrapped in transactions by the package). Initial setup is a bit more involved than STI.

When to use CTI

CTI is the right fit when your subtypes share an identity (a Quiz is an Assessment), share common attributes (title, timestamps), and each type also has its own attributes (passing_score, anonymous). If your types are unrelated entities that just happen to share a relationship, polymorphic relations are the better tool.

License

MIT

pannella/laravel-cti 适用场景与选型建议

pannella/laravel-cti 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2.09k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2025 年 06 月 01 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 pannella/laravel-cti 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-06-01