VOOZH about

URL: https://deepwiki.com/mathsgod/light/9.3.1-model-generation

⇱ Model Generation | mathsgod/light | DeepWiki


Loading...
Last indexed: 31 January 2026 (cf9511)
Menu

Model Generation

Purpose and Scope

The MakeModelCommand generates PHP model classes from database table definitions in db.json, automating the creation of type-safe model classes that integrate with the Light framework's ORM layer. This command eliminates manual model scaffolding and ensures consistency between database schema and PHP code.

For information about the base model class functionality, see Base Model Class (Light\Model). For database schema management, see Database Schema (db.json). For TypeScript interface generation from the same schema, see TypeScript Generation.

Sources: bin/light1-24 db.json1-676


Command Overview

The MakeModelCommand is registered in the Light CLI application and generates PHP model classes that extend Light\Model, providing database access, field accessors, and automatic auditing capabilities.

Command Registration:

bin/light make:model [table_name]

The command reads table definitions from db.json and generates corresponding PHP classes in the project's model directory. Each generated model includes properly typed properties, primary key configuration, and table name mapping.

Sources: bin/light9-10 bin/light19


Schema-Driven Generation Flow


Process Flow: The command reads db.json, parses each table definition, maps database column types to PHP types, and generates a class file that extends Light\Model with all necessary properties and metadata.

Sources: bin/light19 db.json1-676


Database Schema Structure

The db.json file defines tables with the following structure:

Schema ElementDescriptionExample
nameTable name"User", "Role"
columnsArray of column definitionsSee below
primary_keyArray of primary key column names["user_id"]
keysArray of index definitions{"name": "username", "columns": ["username"]}
unique_keysArray of unique constraint definitionsSame structure as keys
foreign_keysArray of foreign key relationshipsIncludes reference table and cascade rules

Column Definition Structure:

PropertyTypeDescription
namestringColumn name (snake_case)
typestringDatabase type: int, varchar, text, datetime, date, json, tinyint, blob
lengthintegerLength for varchar/char types
unsignedbooleanFor integer types
nullablebooleanWhether column allows NULL
auto_incrementbooleanFor primary key columns
defaultstring/numberDefault value

Sources: db.json1-676


Database Type to PHP Type Mapping

The MakeModelCommand maps database column types to appropriate PHP type hints:


Type Mapping Rules:

  • Integers (int, unsigned int): Mapped to PHP int type
  • String types (varchar, text): Mapped to PHP string type
  • Date/time types (datetime, date): Stored as strings in PHP (ISO 8601 format expected)
  • JSON columns: Mapped to PHP array type (automatically serialized/deserialized)
  • Boolean-like (tinyint): Mapped to PHP int (0/1 values)
  • Binary (blob): Mapped to PHP string type
  • Nullable columns: Type hint prefixed with ? (e.g., ?string, ?int)

Sources: db.json1-676


Generated Model Class Structure

For each table in db.json, the MakeModelCommand generates a model class following this structure:


Generated Class Components:

  1. Class Declaration: Extends Light\Model
  2. Table Name Property: protected string $_table = 'TableName';
  3. Primary Key Property: protected string $_primary_key = 'primary_key_column';
  4. Column Properties: Public properties for each column with appropriate type hints
  5. No Methods: Methods are inherited from Light\Model

Sources: db.json1-676


Example: User Model Generation

Given the User table definition in db.json:

Input Schema (db.json):


Generated Output (User.php):


Key Generation Features:

  • Nullable Handling: Columns without "nullable": false get nullable type hints (?string, ?array)
  • JSON Arrays: json column type becomes ?array in PHP
  • Integer Types: Both signed and unsigned integers map to PHP int
  • Auto-increment: Primary key columns are still generated as normal properties
  • Table Metadata: Protected properties $_table and $_primary_key enable ORM functionality

Sources: db.json3-139


Model Relationships and Foreign Keys

The generated models include column properties for foreign keys, but relationship methods are typically added manually:

Foreign Key Example (UserRole table):


Generated UserRole Model:


Manual Relationship Methods can be added after generation:


Sources: db.json179-231


Special Column Handling

Certain columns receive special treatment during generation:


JSON Column Handling:

  • Database stores JSON as text
  • PHP property typed as ?array
  • Light\Model automatically handles json_encode/json_decode on save/load
  • Example: $user->setting = ['theme' => 'dark']; automatically serializes

Datetime/Date Columns:

  • Stored as ?string in PHP
  • Expected format: YYYY-MM-DD HH:MM:SS (datetime) or YYYY-MM-DD (date)
  • Example: $user->created_time = date('Y-m-d H:i:s');

Status/Boolean Columns:

  • tinyint columns typically used for status flags
  • Typed as int in PHP (values 0 or 1)
  • Example: $user->status = 1; // Active

Sources: db.json85-126


Integration with Light\Model Base Class

Generated models inherit comprehensive functionality from Light\Model:


Inherited Functionality:

  1. ORM Operations: User::Get($id), User::Query()->where(...), $user->save(), $user->delete()
  2. Automatic Auditing: created_by, created_time, updated_by, updated_time fields auto-populated
  3. Event Logging: All saves and deletes automatically logged to EventLog table
  4. GraphQL Fields: getField($name) method for lazy-loading and field resolution
  5. Bind Method: $user->bind($_POST) for mass assignment
  6. Lifecycle Hooks: Override beforeSave(), afterSave(), beforeDelete() for custom logic

Sources: db.json1-676


Usage Workflow

Complete Model Generation Workflow:


Step-by-Step Process:

  1. Define Schema: Add or modify table definition in db.json
  2. Run Command: Execute bin/light make:model [TableName]
  3. Verify Output: Check generated model class in models directory
  4. Use Model: Instantiate and use the model with inherited Light\Model functionality
  5. Extend as Needed: Add custom methods, relationships, or business logic to generated class

Sources: bin/light1-24 db.json1-676


Best Practices

Schema Design:

  • Use snake_case for column names (e.g., user_id, created_time)
  • Always define primary keys explicitly
  • Mark nullable columns with "nullable": true to get proper ?Type hints
  • Use json type for complex data structures
  • Include created_time and updated_time for auditing (auto-populated by Light\Model)

Model Customization:

  • Generate base models first, then add custom methods
  • Don't modify generated property declarations (regenerate if schema changes)
  • Override lifecycle hooks (beforeSave(), afterSave()) for business logic
  • Add relationship methods manually (e.g., getUser(), getRoles())
  • Keep database logic in models, not controllers

Code Regeneration:

  • Re-run make:model after schema changes in db.json
  • Custom methods are preserved if placed after generated properties
  • Use version control to track model file changes
  • Test model functionality after regeneration to ensure compatibility

Sources: db.json1-676