Code Generator

The Fuwafuwa Framework includes a powerful Code Generator CLI tool that automates the creation of models, controllers, views, and complete CRUD systems with intelligent schema inspection.

The code generator analyzes your database schema to automatically detect field types, primary keys, timestamps, and validation rules. This eliminates repetitive boilerplate code and ensures consistency across your application. Whether you need a single model or a complete CRUD interface, the generator creates production-ready code in seconds.

✨ Generator Features
  • Schema Inspection - Auto-detects field types, keys, and timestamps from database
  • Smart Validation - Generates validation rules based on NOT NULL constraints
  • Type Detection - Maps SQL types to HTML input types automatically
  • Complete CRUD - Generate model, controller, and view in one command
  • FFTable Ready - Generates fully configured FFTable components

Getting Started

All generator commands follow this pattern:

php index.php cli/codegenerator/<command> --option=value

Output is written to stdout, so you can redirect to files:

php index.php cli/codegenerator/model --name=Product --table=products > app/controllers/user/model/product.php

Get Help

php index.php cli/codegenerator/help

Available Commands

CommandDescription
listList all database tables with row counts
infoShow detailed table schema information
controllerCreate a basic controller
modelCreate a model with schema inspection
migrationCreate a migration class
ajaxcontrollerCreate AJAX controller for FFTable
viewcontrollerCreate view controller with FFTable config
fftableShow commands for FFTable CRUD setup
crudGenerate complete CRUD (with --auto)

Exploring the Database

List All Tables

php index.php cli/codegenerator/list

Output:

  Database Tables

  category       (12 rows)
  customer       (59 rows)
  employee       (8 rows)
  invoice        (224 rows)
  product        (36 rows)
  user           (3 rows)

  Use 'info --table=<name>' to see table schema

Show Table Schema

php index.php cli/codegenerator/info --table=products

Output:

  Table Schema: products

  Primary Key: id
  Auto-Increment: Yes (id)

  Fields:

   * id          : number
    name         : text
    description  : textarea
    price        : number
    category_id  : number
    created_at   : datetime
    updated_at   : datetime

  Detected Mappings:
    created_field: created_at
    modified_field: updated_at

The info command detects primary keys, auto-increment fields, timestamp fields (created_at, updated_at, deleted_at), and maps SQL types to HTML input types. This information is used by other generators to create properly configured code.

Generating Models

Basic Model

php index.php cli/codegenerator/model --name=Product --table=products \
    > app/controllers/user/model/product.php

Generated code includes:

  • Proper namespace and class definition
  • Constructor with detected configuration (ai_field, primary_keys, timestamps)
  • Dependency injection setup

Model with Validations

php index.php cli/codegenerator/model --name=Product --table=products --validations=true \
    > app/controllers/user/model/product.php

Generated validation rules based on schema:

$this->validation = [
    'rules' => [
        'name' => 'required',
        'price' => 'required|numeric',
        'email' => 'required|email',  // auto-detected from field name
    ]
];

Auto-Detected Field Types

SQL TypeHTML InputNotes
INT, BIGINT, DECIMALnumberIncludes tinyint(1) → checkbox
DATEdate
DATETIME, TIMESTAMPdatetime
TIMEtime
BOOLEAN, BITcheckbox
ENUM, SETselect
TEXT, BLOBtextarea
*textDefault fallback

Auto-Detected Timestamp Fields

The generator recognizes these naming patterns:

  • created, created_at, created_datecreated_field
  • updated, updated_at, modified, modified_atmodified_field
  • deleted, deleted_atdeleted_field (soft delete)

Generating Controllers

Basic Controller

php index.php cli/codegenerator/controller --name=ProductController \
    > app/controllers/user/productcontroller.php

Options:

  • --namespace=User - Namespace (default: User)
  • --extends=View - Parent class (default: View)

AJAX Controller for FFTable

php index.php cli/codegenerator/ajaxcontroller --name=Product --table=products \
    > app/controllers/user/ajax/product.php

Options:

  • --withElist=true - Include elist method for custom SQL
  • --csrf=_token - CSRF field name (default: _token)

View Controller with FFTable Config

php index.php cli/codegenerator/viewcontroller --name=Product --table=products \
    > app/controllers/user/product.php

Options:

  • --createView=true - Also generate HTML view file

Generating Complete CRUD

The CRUD generator creates a complete FFTable-based management interface with a single command.

Show CRUD Commands

php index.php cli/codegenerator/crud --name=Product --table=products

This outputs the commands needed to generate all files:

  FFTable CRUD for Product

  Files to generate:
    Model:  app/controllers/user/model/product.php
    Ajax:   app/controllers/user/ajax/product.php
    View:   app/controllers/user/product.php
    HTML:   app/views/user/product.html

  Run the following commands:

    mkdir -p app/controllers/user/model app/controllers/user/ajax app/views/user

Auto-Generate All Files

php index.php cli/codegenerator/crud --name=Product --table=products --auto=true

This creates all files automatically:

  Generating CRUD for Product (table: products)

  Created directory: app/controllers/user/model
  Created directory: app/controllers/user/ajax
  Created directory: app/controllers/user
  Created directory: app/views/user

  Generating files...

  ✓ Model: app/controllers/user/model/product.php
  ✓ Ajax: app/controllers/user/ajax/product.php
  ✓ View: app/controllers/user/product.php

  CRUD generation completed!

  Next steps:
    1. Add route for /product to your routing config
    2. Add route for /ajax/product/* to your routing config
    3. Add menu entry to access the page

Options

  • --withElist=true - Include elist method for custom SQL queries

FFTable Quick Setup

The fftable command shows you exactly what to run:

php index.php cli/codegenerator/fftable --name=Customer --table=customers

Output:

  FFTable CRUD for Customer

  Files to generate:
    Model:  app/controllers/user/model/customer.php
    Ajax:   app/controllers/user/ajax/customer.php
    View:   app/controllers/user/customer.php
    HTML:   app/views/user/customer.html

  Run the following commands:

    mkdir -p app/controllers/user/model app/controllers/user/ajax app/views/user

    # Model
    php index.php cli/codegenerator/model --name=Customer --table=customers > app/controllers/user/model/customer.php

    # Ajax Controller
    php index.php cli/codegenerator/ajaxcontroller --name=Customer --table=customers --withElist=true > app/controllers/user/ajax/customer.php

    # View Controller (with HTML generation)
    php index.php cli/codegenerator/viewcontroller --name=Customer --table=customers --createView=true > app/controllers/user/customer.php

Generating Migrations

php index.php cli/codegenerator/migration --name=add_categories_table \
    > migrations/migration_add_categories_table.php

Generated migration includes:

  • Migration class with SQL trait
  • up() method with CREATE TABLE example
  • down() method with DROP TABLE for rollback
  • Index creation examples

Complete Examples

Example 1: Product Catalog

# 1. Create the database table
cat > migrations/001_create_products_sqlite.sql << 'EOF'
CREATE TABLE IF NOT EXISTS products (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    description TEXT,
    price DECIMAL(10,2) NOT NULL,
    stock INTEGER DEFAULT 0,
    category_id INTEGER,
    is_active INTEGER DEFAULT 1,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_products_category ON products(category_id);
CREATE INDEX idx_products_active ON products(is_active);
EOF

sqlite3 app/db/fuwafuwa.db < migrations/001_create_products_sqlite.sql

# 2. Generate complete CRUD
php index.php cli/codegenerator/crud --name=Product --table=products --auto=true

# 3. Add routes to app/configs/config.ini
# GET|POST /product/* = \User\Product->execute
# GET|POST /ajax/product/* = \Ajax\Product->execute

Example 2: Blog System

# Generate model with validations
php index.php cli/codegenerator/model --name=Post --table=posts --validations=true \
    > app/controllers/user/model/post.php

# Generate AJAX controller
php index.php cli/codegenerator/ajaxcontroller --name=Post --table=posts \
    > app/controllers/user/ajax/post.php

# Generate view controller with HTML
php index.php cli/codegenerator/viewcontroller --name=Post --table=posts --createView=true \
    > app/controllers/user/post.php

Example 3: API Controller

# Generate API-style controller
php index.php cli/codegenerator/controller --name=ApiProduct --namespace=Api --extends=Api \
    > app/controllers/user/api/apiproduct.php

Best Practices

1. Always Use --validations for Models

Validation rules are generated from your schema's NOT NULL constraints. Review and adjust them as needed.

2. Check Generated Code

While the generator creates working code, always review it before committing:

  • Verify field types match your requirements
  • Adjust validation rules if needed
  • Customize the FFTable configuration

3. Use Consistent Naming

  • Model names: Singular PascalCase (Product, Customer, OrderItem)
  • Table names: Plural lowercase (products, customers, order_items)
  • Controller names: Descriptive (ProductController, AdminProductController)

4. Version Control

Generated code should be committed to version control like any other code. This ensures team members have the same implementation.

5. Regenerate After Schema Changes

If you modify the database schema, regenerate the affected files or manually update them to reflect the changes.

Troubleshooting

"Table not found" Error

Ensure the table exists before running generators:

php index.php cli/codegenerator/list

Field Types Not Detected

The generator maps common SQL types. For custom or complex types, manually adjust the generated code.

Permission Denied

Ensure the target directories are writable:

chmod -R 755 app/controllers/user app/views/user

Namespaced Classes

For models in subdirectories, use the full namespace:

# Generate model in Model\Shop namespace
php index.php cli/codegenerator/model --name=Product --table=products > app/controllers/user/model/shop/product.php

# Then manually add namespace: namespace Model\Shop;