rahmatsyaparudin/yii3-api-boilerplate

Yii3 API project template

Fund package maintenance!
Opencollective
yiisoft

Installs: 1

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Type:project-template

pkg:composer/rahmatsyaparudin/yii3-api-boilerplate

v1.0.1 2026-01-28 09:09 UTC

This package is not auto-updated.

Last update: 2026-02-12 05:30:21 UTC


README

Yii3 API Skeleton is a starter project for building RESTful APIs using Yii3 with Domain-Driven Design (DDD) architecture. It provides a ready-to-use structure, helper scripts, and example configurations to accelerate your API development with clean architecture principles.

๐Ÿ—๏ธ Architecture Overview

This skeleton follows Domain-Driven Design (DDD) principles with clean architecture layers:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                    API Layer (Controllers & Middleware)             โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚                Application Layer (Services & Use Cases)             โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚                  Domain Layer (Entities & Business Logic)           โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚               Infrastructure Layer (Repositories & External APIs)   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Key Features

  • ๐ŸŽฏ Domain-Driven Design: Clean separation of business logic
  • ๐Ÿ”ง Type Safety: Full Psalm static analysis integration
  • ๐Ÿงช Testing Ready: Complete test suite setup
  • ๐Ÿ”’ Security: Authentication, authorization, and audit trail
  • ๐Ÿ“Š Quality Assurance: Automated code quality checks
  • ๐Ÿณ Docker Ready: Complete containerization setup
  • ๐Ÿ“š Documentation: Comprehensive documentation included

๐Ÿš€ Quick Start

Prerequisites

  • PHP 8.3+ with required extensions
  • Composer for dependency management
  • PostgreSQL database
  • MongoDB (optional, for audit trails)
  • Docker (optional, for containerized development)

1. Create New Project

composer create-project --prefer-dist yiisoft/app-api ./

2. Add the repository and package to composer.json

Open your project's composer.json and add the following sections:

Add this to composer.json repositories

"repositories": [
        {
            "type": "composer",
            "url": "https://asset-packagist.org"
        },
        {
            "type": "vcs",
            "url": "https://github.com/rahmatsyaparudin/yii3-api-boilerplate.git"
        }
    ],

Add this to composer.json require-dev

"rahmatsyaparudin/yii3-api-boilerplate": "dev-main"

Add this to composer.json scripts

"skeleton-scripts": [
    "@php scripts/skeleton-scripts.php"
],
"skeleton-update": [
    "composer update rahmatsyaparudin/yii3-api-boilerplate --ignore-platform-reqs",
    "@php scripts/skeleton-scripts.php",
    "@php scripts/skeleton-update.php"
],
"skeleton-copy-config": [
    "@php scripts/skeleton-copy-config.php"
],
"skeleton-copy-examples": [
    "@php scripts/skeleton-copy-examples.php"
],
"skeleton-generate-module": [
    "@php scripts/generate-module.php"
]

3. Update Composer

Update composer dependencies

composer update --ignore-platform-reqs

4. Copy skeleton scripts

Make directory scripts and Copy the scripts folder from the package to your project root:

mkdir scripts; cp -r -Force vendor/rahmatsyaparudin/yii3-api-boilerplate/scripts/* ./scripts

5. Install Skeleton

Install skeleton structure

composer skeleton-update

Copy config files (first time only)

composer skeleton-copy-config

Copy example files (first time only)

composer skeleton-copy-examples

6. Generate New Module

Use the built-in module generator to create new API modules with complete structure: Generate a new module (e.g., Product)

composer skeleton-generate-module -- --module=Product --table=product_management

Or use direct PHP script (alternative):

php scripts/generate-module.php --module=Product --table=product_management

Note: The skeleton comes with an Example module that demonstrates the complete structure. Use the generator above to create additional modules for your specific needs.

What the Generator Creates

The module generator creates a complete module structure following DDD architecture. Here's what you get when generating a new module (based on the existing Example module):

๐Ÿ“ API Layer (src/Api/V1/{Module}/)

src/Api/V1/Product/
โ”œโ”€โ”€ Action/
โ”‚   โ”œโ”€โ”€ ProductCreateAction.php    # POST /product/create
โ”‚   โ”œโ”€โ”€ ProductDataAction.php      # GET/POST /product & /product/data
โ”‚   โ”œโ”€โ”€ ProductDeleteAction.php    # DELETE /product/{id}
โ”‚   โ”œโ”€โ”€ ProductRestoreAction.php   # POST /product/{id}/restore
โ”‚   โ”œโ”€โ”€ ProductUpdateAction.php    # PUT /product/{id}
โ”‚   โ””โ”€โ”€ ProductViewAction.php      # GET /product/{id}
โ””โ”€โ”€ Validation/
    โ””โ”€โ”€ ProductInputValidator.php  # Request validation rules

๐Ÿ“ Application Layer (src/Application/{Module}/)

src/Application/Product/
โ”œโ”€โ”€ Command/
โ”‚   โ”œโ”€โ”€ CreateProductCommand.php   # Create command DTO
โ”‚   โ””โ”€โ”€ UpdateProductCommand.php   # Update command DTO
โ”œโ”€โ”€ Dto/
โ”‚   โ””โ”€โ”€ ProductResponse.php        # Response DTO
โ””โ”€โ”€ ProductApplicationService.php # Application service

๐Ÿ“ Domain Layer (src/Domain/{Module}/)

src/Domain/Product/
โ”œโ”€โ”€ Entity/
โ”‚   โ””โ”€โ”€ Product.php               # Domain entity
โ”œโ”€โ”€ Repository/
โ”‚   โ””โ”€โ”€ ProductRepositoryInterface.php # Repository interface
โ””โ”€โ”€ Service/
    โ””โ”€โ”€ ProductDomainService.php  # Domain service

๐Ÿ“ Infrastructure Layer (src/Infrastructure/Persistence/{Module}/)

src/Infrastructure/Persistence/Product/
โ”œโ”€โ”€ ProductRepository.php         # Repository implementation
โ””โ”€โ”€ MdbProductSchema.php          # MongoDB schema

๐Ÿ“ Database & Seeding

src/Migration/
โ””โ”€โ”€ M20240130123457CreateProductTable.php  # Database migration

src/Seeder/
โ”œโ”€โ”€ SeedProductData.php           # Seeder class
โ””โ”€โ”€ Fixtures/
    โ””โ”€โ”€ product.yaml              # Alice fixtures for test data

โš™๏ธ Configuration Updates

The generator automatically updates configuration files:

  • config/common/access.php - Adds access control rules
  • config/common/aliases.php - Adds aliases
  • config/common/routes.php - Adds API routes with proper permissions
  • config/common/di/repository.php - Adds repository DI binding
  • config/common/di/service.php - Adds service DI binding
  • config/common/di/translator.php - Adds translator DI binding
  • config/console/commands.php - Adds console commands

๐Ÿ”ง Features Included

  • โœ… Complete CRUD Operations - Create, Read, Update, Delete, Restore
  • โœ… RESTful API Endpoints - Following REST conventions
  • โœ… Request Validation - Input validation rules
  • โœ… Permission System - Role-based access control
  • โœ… Database Migration - Schema management
  • โœ… Data Seeding - Test data generation with Alice fixtures
  • โœ… Type Safety - Full Psalm compatibility
  • โœ… Error Handling - Standardized error responses

Generated API Endpoints

For each module, the following endpoints are automatically created:

Method Endpoint Action Permission
GET /v1/{module} List items {module}.index
POST /v1/{module}/data Create item {module}.data
GET /v1/{module}/{id} View item {module}.view
POST /v1/{module}/create Create item {module}.create
PUT /v1/{module}/{id} Update item {module}.update
DELETE /v1/{module}/{id} Delete item {module}.delete
POST /v1/{module}/{id}/restore Restore item {module}.restore

๐Ÿ“‹ Current Available Modules

The skeleton includes the following modules out of the box:

โœ… Example Module (Included)

  • Purpose: Demonstrates complete module structure
  • Endpoints: /v1/example/*
  • Usage: Reference implementation for learning and testing
  • Files: Complete DDD structure with all layers

๐Ÿ”ง Custom Modules (Generate as needed)

  • Product, Category, Brand, Order, User, etc.
  • Purpose: Your business-specific modules
  • Generation: Use composer skeleton-generate-module -- --module=ModuleName --table=table_name or php scripts/generate-module.php --module=ModuleName --table=table_name
  • Custom Table: Use --table=table_name for table names (e.g., --module=Product --table=product_management)
  • Customization: Modify generated files according to your business logic

๐Ÿ“ Project Structure

After installation, your project will have this structure:

yii3-api/
โ”œโ”€โ”€ config/                 # Application configuration
โ”‚   โ”œโ”€โ”€ common/             # Shared configuration
โ”‚   โ”œโ”€โ”€ console/            # Console configuration
โ”‚   โ”œโ”€โ”€ environments/       # Environment configs
โ”‚   โ””โ”€โ”€ web/                # Web configuration
โ”œโ”€โ”€ docs/                   # Documentation
โ”‚   โ”œโ”€โ”€ architecture-guide.md # Architecture documentation
โ”‚   โ”œโ”€โ”€ quality-guide.md    # Quality assurance guide
โ”‚   โ””โ”€โ”€ setup-guide.md     # This setup guide
โ”œโ”€โ”€ public/                 # Web root
โ”‚   โ””โ”€โ”€ index.php          # Application entry point
โ”œโ”€โ”€ resources/              # Application resources
โ”‚   โ””โ”€โ”€ messages/           # Translation files
โ”œโ”€โ”€ scripts/                # Utility scripts
โ”‚   โ”œโ”€โ”€ generate-module.php # Module generator
โ”‚   โ”œโ”€โ”€ skeleton-update.php # Skeleton installer
โ”‚   โ”œโ”€โ”€ skeleton-copy-examples.php # Example files copier
โ”‚   โ””โ”€โ”€ skeleton-copy-config.php # Config files copier
โ”œโ”€โ”€ src/                    # Source code
โ”‚   โ”œโ”€โ”€ Api/                # API layer
โ”‚   โ”‚   โ”œโ”€โ”€ V1/             # API version 1
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ Example/    # Example API endpoints
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ Shared/     # Shared API components
โ”‚   โ”‚   โ””โ”€โ”€ Shared/         # Shared API components
โ”‚   โ”œโ”€โ”€ Application/        # Application layer
โ”‚   โ”‚   โ”œโ”€โ”€ Example/        # Application services
โ”‚   โ”‚   โ””โ”€โ”€ Shared/         # Shared application services
โ”‚   โ”œโ”€โ”€ Domain/             # Domain layer
โ”‚   โ”‚   โ”œโ”€โ”€ Example/        # Domain entities
โ”‚   โ”‚   โ””โ”€โ”€ Shared/         # Shared domain components
โ”‚   โ”œโ”€โ”€ Infrastructure/      # Infrastructure layer
โ”‚   โ”‚   โ”œโ”€โ”€ Audit/         # Audit services
โ”‚   โ”‚   โ”œโ”€โ”€ Database/      # Database implementations
โ”‚   โ”‚   โ”œโ”€โ”€ Persistence/   # Repository implementations
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ Example/    # Example repository
โ”‚   โ”‚   โ””โ”€โ”€ Security/      # Security services
โ”‚   โ”œโ”€โ”€ Migration/          # Database migrations
โ”‚   โ”‚   โ””โ”€โ”€ M20240101000000CreateExampleTable.php
โ”‚   โ”œโ”€โ”€ Seeder/            # Data seeders
โ”‚   โ”‚   โ”œโ”€โ”€ Fixtures/      # Alice fixtures
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ example.yaml
โ”‚   โ”‚   โ”œโ”€โ”€ Faker/         # Faker providers
โ”‚   โ”‚   โ””โ”€โ”€ SeedExampleData.php
โ”‚   โ””โ”€โ”€ Shared/            # Shared utilities
โ”œโ”€โ”€ tests/                  # Test suite
โ”‚   โ”œโ”€โ”€ Api/                # API tests
โ”‚   โ”œโ”€โ”€ Functional/         # Functional tests
โ”‚   โ”œโ”€โ”€ Support/            # Test support classes
โ”‚   โ””โ”€โ”€ Unit/              # Unit tests
โ””โ”€โ”€ vendor/                 # Dependencies

๐Ÿ”ง Configuration

Environment Setup

1. Copy Environment Files

# Copy environment configuration
cp .env.example .env

2. Configure Environment

Edit .env file:

# Application Environment
APP_ENV=dev
APP_DEBUG=1

app.config.code=appAPI
app.config.name=appAPI
app.config.language=en
app.time.timezone=Asia/Jakarta
app.pagination.defaultPageSize=10
app.pagination.maxPageSize=100
app.rateLimit.maxRequests=100
app.rateLimit.windowSize=60
app.hsts.maxAge=31536000
app.hsts.includeSubDomains=true
app.hsts.preload=false
app.cors.allowedOrigins=["http://example.com:3000"]
app.cors.maxAge=86400
app.cors.allowCredentials=true
app.cors.allowedMethods=["GET","POST","PUT","PATCH","DELETE","OPTIONS"]
app.cors.allowedHeaders=["Content-Type","Authorization","X-Requested-With","Accept","Origin"]
app.cors.exposedHeaders=["X-Pagination-Total-Count","X-Pagination-Page-Count"]
app.trusted_hosts.allowedHosts=["127.0.0.1","::1","localhost"]

# Optimistic Lock Configuration
app.optimistic_lock.enabled=true
app.optimistic_lock.disabled.values=["example","example_1"]

# SSO Configuration (External Keycloak)
app.jwt.secret=secret-key-harus-panjang-256-bit
app.jwt.algorithm=HS256
app.jwt.issuer=https://sso.example.com
app.jwt.audience=https://sso.example.com

db.default.driver=pgsql
db.default.host=localhost
db.default.port=5432
db.default.name=dev_yii3
db.default.user=postgres
db.default.password=postgres

db.mongodb.dsn=localhost:27017
db.mongodb.name=db_example
db.mongodb.enabled=true

redis.default.host=127.0.0.1
redis.default.port=6379
redis.default.db=0
redis.default.password=null

3. Database Migration

# Run database migrations
./yii migrate:up

# Seed initial data (development only)
./yii seed --module=example

# Or seed with custom options (development only)
./yii seed --module=example --count=10

# Note: Seed commands only work in development environment (APP_ENV=dev)

4. Optimistic Lock Configuration

The skeleton includes configurable optimistic locking to prevent concurrent update conflicts:

# Enable/disable optimistic locking (global)
app.optimistic_lock.enabled=true    # Default: true

# Disable optimistic locking for specific validators (JSON array)
app.optimistic_lock.disabled.values=["example","example_1"]

๐Ÿ”ง Optimistic Lock Features:

  • โœ… Automatic Version Management - Each entity has a lock_version field
  • โœ… Concurrent Update Prevention - Throws exception on version mismatch
  • โœ… Configurable - Can be enabled/disabled globally or per validator
  • โœ… Performance Optimized - Skips verification when disabled
  • โœ… Per-Validator Control - Fine-grained control per validator type
  • โœ… Smart Normalization - Automatic validator name normalization

๐Ÿ“‹ Configuration Options:

Setting Type Default Description
app.optimistic_lock.enabled boolean true Enable/disable optimistic locking globally
app.optimistic_lock.disabled.values JSON array [] List of disabled validators (normalized names)

๐Ÿš€ Usage Examples:

# Disable optimistic locking globally
app.optimistic_lock.enabled=false

# Disable for specific validators
app.optimistic_lock.disabled.values=["example","user","product"]

# Enable all validators (empty disabled list)
app.optimistic_lock.disabled.values=[]

# Enable in production for data integrity
app.optimistic_lock.enabled=true
app.optimistic_lock.disabled.values=[]

๐Ÿ”ง Validator Name Normalization:

The system automatically normalizes validator names for configuration:

// Validator Class โ†’ Normalized Name โ†’ Environment Key
ExampleInputValidator โ†’ "example" โ†’ app.optimistic_lock.disabled.values=["example"]
UserInputValidator โ†’ "user" โ†’ app.optimistic_lock.disabled.values=["user"]
ProductInputValidator โ†’ "product" โ†’ app.optimistic_lock.disabled.values=["product"]

๐Ÿ”ง Implementation in Validators:

Optimistic lock validation is automatically integrated into validators:

// In your InputValidator class
final class ExampleInputValidator extends AbstractValidator
{
    protected function rules(string $context): array
    {
        return match ($context) {
            ValidationContext::UPDATE => [
                'id' => [new Required(), new Integer(min: 1)],
                'name' => [new StringValue(skipOnEmpty: true)],
                // Unique validation with optimistic lock awareness
                'name' => [
                    new Required(),
                    new StringValue(),
                    new UniqueValue(
                        targetClass: ExampleRepository::class,
                        targetAttribute: 'name',
                        filter: fn() => $this->getFilterForUnique(),
                        // Automatically respects optimistic lock configuration
                        skipOnEmpty: fn() => !$this->isOptimisticLockEnabled()
                    ),
                ],
                // lock_version automatically added/removed based on configuration
                'lock_version' => [
                    new Required(
                        when: fn() => $this->isOptimisticLockEnabled()
                    ),
                    new Integer(
                        min: 1,
                        skipOnEmpty: fn() => !$this->isOptimisticLockEnabled()
                    ),
                ],
            ],
            // ... other contexts
        };
    }
}

๐Ÿ”ง Advanced Validation Features:

The system includes advanced validation rules that integrate with optimistic locking:

// UniqueValue Rule - Prevents duplicate names with optimistic lock support
new UniqueValue(
    targetClass: ExampleRepository::class,
    targetAttribute: 'name',
    filter: fn() => $this->getFilterForUnique(),
    message: 'Name must be unique',
    skipOnEmpty: true
)

// HasNoDependencies Rule - Validates entity has no dependencies before deletion
new HasNoDependencies(
    dependencyChecker: $this->dependencyChecker,
    errorMessage: 'Cannot delete entity with existing dependencies',
    skipOnEmpty: false
)

๐Ÿ”ง Implementation in Entities:

Entities use the OptimisticLock trait for automatic version management:

// In your Entity class
use App\Domain\Shared\Concerns\Entity\OptimisticLock;

final class Example extends Entity
{
    use OptimisticLock;
    
    // Automatic lock_version management
    // - verifyLockVersion() for validation
    // - upgradeLockVersion() for increment
    // - getLockVersion() for current version
}

๐Ÿ“ Configuration Examples:

# Development: Disable for testing entities
app.optimistic_lock.enabled=true
app.optimistic_lock.disabled.values=["example","test"]

# Production: Enable for all entities
app.optimistic_lock.enabled=true
app.optimistic_lock.disabled.values=[]

# Maintenance: Disable all optimistic locking
app.optimistic_lock.enabled=false

๐Ÿ”ง API Usage:

When optimistic locking is enabled, include lock_version in UPDATE/DELETE requests:

# Update with optimistic lock
curl -X PUT http://localhost:8080/v1/example/1 \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Updated Name",
    "lock_version": 5
  }'

# Delete with optimistic lock
curl -X DELETE http://localhost:8080/v1/example/1 \
  -H "Content-Type: application/json" \
  -d '{"lock_version": 5}'

When disabled for a validator, lock_version is optional:

# Update without lock_version (when disabled)
curl -X PUT http://localhost:8080/v1/example/1 \
  -H "Content-Type: application/json" \
  -d '{"name": "Updated Name"}'

---

## ๐ŸŽฏ Development Workflow

### Quality Assurance

The skeleton includes comprehensive quality assurance tools:

```bash
# Run complete quality check suite
php quality quality:check

# Auto-fix code style issues
php quality quality:check --fix

# Generate test coverage reports
php quality quality:check --coverage

# Generate detailed analysis reports
php quality quality:check --report

Testing

# Run all tests
vendor/bin/phpunit

# Run specific test suite
vendor/bin/phpunit tests/Unit/
vendor/bin/phpunit tests/Api/
vendor/bin/phpunit tests/Functional/

# Run tests with coverage
vendor/bin/phpunit --coverage-html tests/coverage/html

Static Analysis

# Run Psalm static analysis
vendor/bin/psalm

# Clear cache and re-run
vendor/bin/psalm --clear-cache

# Check specific file
vendor/bin/psalm src/Domain/Example/Entity/Example.php

๐Ÿ—๏ธ Architecture Components

Domain Layer

The domain layer contains business logic and entities:

// src/Domain/Example/Entity/Example.php
final class Example
{
    use Identifiable, Stateful, OptimisticLock;
    
    public static function create(string $name, Status $status, DetailInfo $detailInfo): self
    {
        self::guardInitialStatus($status, null, self::RESOURCE);
        return new self(null, $name, $status, $detailInfo, null, LockVersion::create());
    }
}

Application Layer

Application services coordinate use cases:

// src/Application/Example/ExampleApplicationService.php
final class ExampleApplicationService
{
    public function create(CreateExampleCommand $command): ExampleResponse
    {
        // Business logic validation
        $this->domainService->validateUniqueValue(...);
        
        // Entity creation
        $example = Example::create(...);
        
        // Persistence
        return ExampleResponse::fromEntity($this->repository->insert($example));
    }
}

Infrastructure Layer

Repository implementations handle data persistence:

// src/Infrastructure/Persistence/Example/ExampleRepository.php
final class ExampleRepository implements ExampleRepositoryInterface
{
    public function insert(Example $example): Example
    {
        return $this->db->transaction(function() use ($example) {
            // Database operations with MongoDB sync
        });
    }
}

API Layer

Controllers handle HTTP requests:

// src/Api/V1/Action/Example/ExampleCreateAction.php
final class ExampleCreateAction
{
    public function run(ServerRequestInterface $request): ResponseInterface
    {
        // Request validation
        $command = new CreateExampleCommand(...);
        
        // Business logic
        $response = $this->applicationService->create($command);
        
        // Response formatting
        return $this->responseFactory->success($response->toArray());
    }
}

๐Ÿ”’ Security Features

Authentication & Authorization

// JWT Authentication
$app->addMiddleware(new AuthenticationMiddleware($jwtAuthenticator));

// RBAC Authorization
$app->addMiddleware(new AuthorizationMiddleware($rbacAuthorizer));

Audit Trail

// Automatic audit logging
final class DatabaseAuditService implements AuditServiceInterface
{
    public function log(string $tableName, int $recordId, string $action, ?array $oldValues = null, ?array $newValues = null): void
    {
        // Log to database with actor information
    }
}

๐Ÿš€ API Usage Examples

Create Resource

curl -X POST http://localhost:8080/api/v1/examples \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "name": "Example Resource",
    "status": "active",
    "detail_info": {
      "description": "Example description"
    }
  }'

List Resources

curl -X GET "http://localhost:8080/api/v1/examples?page=1&pageSize=10&sort=name&dir=asc" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

Update Resource

curl -X PUT http://localhost:8080/api/v1/examples/1 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "name": "Updated Resource",
    "lock_version": 1
  }'

Delete Resource

curl -X DELETE http://localhost:8080/api/v1/examples/1 \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

๐Ÿณ Docker Development

Development Environment

# Start development containers
docker-compose -f docker/dev/compose.yml up -d

# Run commands in container
docker-compose -f docker/dev/compose.yml exec app php yii migrate
docker-compose -f docker/dev/compose.yml exec app php quality

Production Environment

# Build and run production containers
docker-compose -f docker/prod/compose.yml up -d --build

# View logs
docker-compose -f docker/prod/compose.yml logs -f

๐Ÿ“š Documentation

Available Documentation

Generating Documentation

# Run quality checks with coverage
php quality quality:check --coverage

# Run quality checks with detailed reports
php quality quality:check --report

# Run quality checks with both coverage and reports
php quality quality:check --coverage --report

# Fix code style issues automatically
php quality quality:check --fix

๐Ÿงช Testing Strategy

Test Types

  1. Unit Tests: Test individual classes and methods
  2. Functional Tests: Test application workflows
  3. API Tests: Test API endpoints
  4. Integration Tests: Test database and external service integration

Running Tests

# Run all tests using quality script
php quality test:run

# Run only unit tests
php quality test:run --unit

# Run only integration tests
php quality test:run --integration

# Run tests with coverage
php quality test:run --coverage

# Run specific test with filter
php quality test:run --filter=ExampleTest

# Alternative: Direct PHPUnit commands
vendor/bin/phpunit
vendor/bin/phpunit --coverage-html tests/coverage/html
vendor/bin/phpunit tests/Unit/Domain/Example/ExampleTest.php

๐Ÿ”ง Maintenance

Regular Tasks

Weekly

  • Update dependencies: composer update
  • Run quality checks: php quality
  • Review test coverage trends
  • Check security advisories

Monthly

  • Review and update quality configuration
  • Update coding standards
  • Add new quality checks as needed
  • Performance optimization review

Quarterly

  • Major dependency updates
  • Quality gate threshold reviews
  • Tool version upgrades
  • Architecture review meetings

Troubleshooting

Common Issues

# Clear all caches
vendor/bin/psalm --clear-cache

# Reinstall dependencies
composer install --no-dev --optimize-autoloader

๐Ÿ“ž Support & Resources

Documentation

Community

Quality Tools

๐ŸŽฏ Best Practices

Code Quality

  • Type Safety: Always use strict types and type annotations
  • Error Handling: Implement proper exception handling
  • Testing: Maintain high test coverage (>80%)
  • Documentation: Keep documentation up-to-date

Security

  • Input Validation: Validate all user inputs
  • Authentication: Use JWT tokens for API authentication
  • Authorization: Implement RBAC for access control
  • Audit Trail: Log all important operations

Performance

  • Database Optimization: Use proper indexes and query optimization
  • Caching: Implement multi-level caching strategy
  • Async Processing: Use queues for long-running operations
  • Monitoring: Monitor application performance

๐ŸŽ‰ Conclusion

The Yii3 API Skeleton provides a solid foundation for building modern, scalable, and maintainable RESTful APIs with Domain-Driven Design principles. The included quality assurance tools, comprehensive documentation, and clean architecture patterns ensure that your API development follows best practices from day one.

Key benefits:

  • ๐Ÿ—๏ธ Clean Architecture: DDD principles for maintainable code
  • ๐Ÿ”’ Type Safety: Full static analysis with Psalm
  • ๐Ÿงช Testing Ready: Complete test suite setup
  • ๐Ÿ“Š Quality Assurance: Automated quality checks
  • ๐Ÿณ Docker Ready: Containerization support
  • ๐Ÿ“š Comprehensive Docs: Complete documentation included

Start building your next API project with confidence using the Yii3 API Skeleton! ๐Ÿš€