Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Sti Laravel Package

mannikj/laravel-sti

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Single Table Inheritance (STI) Alignment: The package aligns well with Laravel’s Eloquent ORM and PHP’s object-oriented design, particularly for scenarios requiring polymorphic behavior (e.g., shared attributes across related models with distinct logic). Ideal for domain models with hierarchical relationships (e.g., VehicleCar, Truck).
  • Laravel Ecosystem Synergy: Leverages Laravel’s built-in Blueprint macros and Eloquent’s existing STI capabilities, reducing friction with native tooling (e.g., migrations, queries).
  • Limitation: Not suitable for deep inheritance hierarchies or cases requiring complex discriminator logic (e.g., dynamic type resolution).

Integration Feasibility

  • Low-Coupling Design: The trait-based approach avoids modifying core Laravel files, adhering to the "compose over inherit" principle.
  • Migration Support: The sti() macro simplifies schema changes, but requires manual validation of existing type columns (e.g., legacy databases).
  • Query Optimization: Automatically resolves model subclasses, but complex joins/relationships may need manual handling (e.g., polymorphic belongsTo).
  • Testing Overhead: STI can complicate unit tests (e.g., mocking subclasses), requiring adjustments to test suites.

Technical Risk

  • Performance: STI queries may degrade with large tables due to WHERE type = ? clauses. Indexing the type column mitigates this.
  • Data Integrity: Incorrect type values or missing subclasses can cause runtime errors (e.g., ClassNotFoundException). Validation logic must be added.
  • Schema Lock-in: Adding/removing subclasses requires migrations, risking downtime in production.
  • Dependency Risk: Minimal (MIT license, active maintenance), but Laravel version compatibility must be monitored (e.g., Eloquent changes).

Key Questions

  1. Use Case Validation:
    • Is STI the best fit, or would Class Table Inheritance (CTI) or polymorphic associations serve the domain better?
    • Will the hierarchy depth exceed 3–4 levels (risking maintenance complexity)?
  2. Migration Strategy:
    • How will existing data be backfilled into the type column without downtime?
    • Are there constraints on altering production schemas?
  3. Query Patterns:
    • Will most queries target subclasses directly, or will root-model queries dominate (impacting performance)?
  4. Testing:
    • How will the team adapt test suites to handle dynamic subclass resolution?
  5. Monitoring:
    • Are there plans to track STI-related query performance (e.g., slow type lookups)?

Integration Approach

Stack Fit

  • Laravel Version: Confirmed compatibility with Laravel 10.x (check composer.json constraints). Test against the target Laravel version.
  • PHP Version: Requires PHP 8.1+ (aligns with Laravel’s current support).
  • Database: Works with all Eloquent-supported databases (MySQL, PostgreSQL, SQLite), but type column constraints (e.g., ENUM) may need adjustment.
  • Tooling:
    • Laravel Scout: STI may conflict with global search indexing; subclass-specific indexing may be needed.
    • Laravel Nova/Vue: UI components must handle dynamic model types (e.g., polymorphic resource resolution).

Migration Path

  1. Schema Update:
    • Add type column to the target table using the sti() macro:
      Schema::table('vehicles', function (Blueprint $table) {
          $table->sti()->nullable(); // or ->default('vehicle')
      });
      
    • For existing data, use a data migration to populate type values:
      DB::table('vehicles')->update(['type' => 'car']); // Example
      
  2. Model Refactoring:
    • Apply the trait to the root model:
      class Vehicle extends Model {
          use SingleTableInheritance;
      }
      
    • Extend subclasses:
      class Car extends Vehicle {}
      class Truck extends Vehicle {}
      
  3. Dependency Injection:
    • Register the package service provider in config/app.php (handled automatically via composer require).
  4. Validation:
    • Add a booted() method to the root model to validate type values:
      protected static function booted() {
          static::addGlobalScope('ValidType', function (Builder $builder) {
              $builder->whereIn('type', ['car', 'truck']);
          });
      }
      

Compatibility

  • Existing Code:
    • Queries using Vehicle::all() will return mixed Car/Truck instances. Update type hints and casts accordingly.
    • Polymorphic relationships (e.g., Vehicle::morphMany()) may need adjustments to handle subclasses.
  • Third-Party Packages:
    • Packages relying on strict model type resolution (e.g., some audit logs) may break. Test thoroughly.
    • Cache drivers (e.g., Redis) may serialize mixed model types unpredictably; use model_keys or custom serialization.

Sequencing

  1. Development Phase:
    • Implement STI in a feature branch with a new table (e.g., vehicles_sti) to test patterns.
    • Gradually migrate queries to use STI, starting with read-heavy operations.
  2. Staging Validation:
    • Load-test with production-like data volumes to measure query performance.
    • Verify subclass-specific logic (e.g., Car::validate()) works as expected.
  3. Production Rollout:
    • Deploy schema changes during low-traffic periods.
    • Use feature flags to toggle STI for specific models before full adoption.
    • Monitor for ClassNotFoundException or query timeouts.

Operational Impact

Maintenance

  • Model Hierarchy:
    • Adding/removing subclasses requires migrations and potential downtime. Document the process and enforce a review gate.
    • Use a type column with an ENUM or constrained set to prevent invalid values.
  • Deprecation:
    • Plan for subclass deprecation (e.g., archive type values) to avoid orphaned data.
  • Tooling:
    • Update IDE hints (e.g., PHPStorm) to recognize dynamic return types from STI queries.

Support

  • Debugging:
    • STI-related issues (e.g., wrong subclass resolution) may require inspecting the type column and model inheritance chain.
    • Log subclass instantiation paths for complex hierarchies:
      class Vehicle extends Model {
          protected static function booted() {
              static::creating(function ($model) {
                  logger()->debug("Creating {$model->type} (class: " . get_class($model) . ")");
              });
          }
      }
      
  • Documentation:
    • Maintain a runbook for common STI pitfalls (e.g., missing type values, circular dependencies).
    • Highlight limitations (e.g., no STI with hasOne/belongsTo without workarounds).

Scaling

  • Performance:
    • Index the type column:
      Schema::table('vehicles', function (Blueprint $table) {
          $table->string('type')->index();
      });
      
    • Avoid SELECT * on large STI tables; explicitly load only needed attributes.
    • For read-heavy workloads, consider denormalizing subclass-specific fields.
  • Database:
    • STI tables may grow large; monitor row count and query performance.
    • Partitioning by type (if supported by the DB) can help with scaling.

Failure Modes

Failure Scenario Impact Mitigation
Invalid type value in DB Runtime ClassNotFoundException Add global scope to filter invalid types.
Missing subclass definition Silent failures or errors Use a fallback root model or throw exceptions.
Unindexed type column Slow queries Add index during migration.
Circular subclass dependencies Infinite loops in logic Enforce linear inheritance in code reviews.
Cache corruption (serialized models) Inconsistent data retrieval Avoid caching mixed model types; use model_keys.

Ramp-Up

  • Team Training:
    • Conduct a workshop on STI patterns, including:
      • When to use STI vs. alternatives (e.g., polymorphic relationships).
      • Debugging subclass resolution issues.
      • Performance tuning (indexing, query optimization).
    • Provide cheat sheets for common operations (e.g., querying subclasses, migrations).
  • Onboarding:
    • Include STI in the project’s architecture decision records (ADRs).
    • Document the hierarchy in a MODELS.md file with subclass relationships.
  • Pair Programming:
    • Pair new hires with senior devs to review STI-related PRs initially.
    • Encourage code reviews to catch potential subclass issues early.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime