PHPackages                             lengthofrope/treehouse - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. lengthofrope/treehouse

ActiveLibrary

lengthofrope/treehouse
======================

TreeHouse - Modern PHP Framework with Zero Dependencies

174[3 issues](https://github.com/lengthofrope/treehouse/issues)PHP

Since Jun 28Pushed 8mo agoCompare

[ Source](https://github.com/lengthofrope/treehouse)[ Packagist](https://packagist.org/packages/lengthofrope/treehouse)[ RSS](/packages/lengthofrope-treehouse/feed)WikiDiscussions develop Synced 1mo ago

READMEChangelogDependenciesVersions (6)Used By (0)

TreeHouse PHP Framework
=======================

[](#treehouse-php-framework)

A modern, lightweight PHP framework built from scratch with zero external dependencies, featuring a comprehensive layered architecture.

WORK IN PROGRESS
----------------

[](#work-in-progress)

Please note that this framework is in active development state. While many features are implemented and extensively tested, it is not yet production ready. Use for development, learning, and experimentation purposes.

**Current Status**: Major features including JWT authentication, ORM, templating, events system, mail system, and rate limiting are completed with extensive test coverage (1900+ tests).

Architecture Overview
---------------------

[](#architecture-overview)

TreeHouse Framework is built with a clean layered architecture consisting of 16 core layers, plus advanced middleware systems, making it a comprehensive 17+ component framework. Each layer provides specific functionality and maintains clear separation of concerns:

### Core Layers

[](#core-layers)

1. **[Foundation Layer](src/TreeHouse/Foundation/README.md)**

    - Application bootstrap and lifecycle management
    - Dependency injection container with auto-wiring
    - Service registration and configuration loading
    - Environment management and application setup
2. **[Database Layer](src/TreeHouse/Database/README.md)**

    - ActiveRecord ORM with Eloquent-style syntax
    - Fluent QueryBuilder for complex SQL operations
    - Database connections and transaction management
    - Schema migrations and relationship handling
3. **[Router Layer](src/TreeHouse/Router/README.md)**

    - HTTP routing with parameter binding and constraints
    - Middleware system for request/response processing
    - Route groups, named routes, and URL generation
    - RESTful routing patterns and route caching
4. **[Auth Layer](src/TreeHouse/Auth/README.md)**

    - **Enterprise JWT Authentication** - RFC 7519 compliant stateless authentication
    - **Multi-Guard System** - Session and JWT guards with flexible switching
    - **Role-Based Access Control (RBAC)** - Complete permission system
    - **Multi-Algorithm JWT** - HS256/384/512, RS256/384/512, ES256/384/512 support
    - **Stateless Authentication** - Pure stateless JWT authentication for APIs
    - **Multi-Source Token Extraction** - Header, cookie, query parameter support
5. **[Console Layer](src/TreeHouse/Console/README.md)**

    - Comprehensive CLI application framework
    - **JWT Management Commands** - Generate, validate, decode, security audit
    - Built-in commands for user and cache management
    - Database migration and development tools
    - Interactive command system with argument parsing
6. **[Cron Layer](src/TreeHouse/Cron/README.md)**

    - Task scheduling and cron job management
    - Automated background task execution
    - Job queuing and processing system
    - Scheduled command execution
7. **[Errors Layer](src/TreeHouse/Errors/README.md)**

    - Comprehensive error handling and exception management
    - PSR-3 compliant logging with structured data
    - Multi-format error rendering (JSON, HTML, CLI)
    - Production-ready error handling
8. **[Mail Layer](src/TreeHouse/Mail/README.md)**

    - **Complete Email System** - SMTP, Sendmail, Log drivers
    - **Database Queue System** - Automated processing with retry logic
    - **Laravel-style Mailables** - TreeHouse template integration
    - **File Attachments** - Security validation and MIME detection
    - **Event Integration** - Monitoring and control
    - **CLI Management** - Queue commands and email generation
9. **[Models Layer](src/TreeHouse/Models/README.md)**

    - Base model classes and utilities
    - Model relationships and data handling
    - Database interaction patterns
    - Advanced model features and helpers
10. **[Cache Layer](src/TreeHouse/Cache/README.md)**

    - High-performance file-based caching
    - Pattern matching and wildcard cache operations
    - Cache prefixing and namespace organization
    - TTL support and automatic cleanup
11. **[Http Layer](src/TreeHouse/Http/README.md)**

    - HTTP request and response handling
    - Session management with security features
    - Cookie handling and file upload processing
    - Security headers and HTTPS enforcement
12. **[Security Layer](src/TreeHouse/Security/README.md)**

    - CSRF protection with token validation
    - AES-256-CBC encryption for sensitive data
    - Secure password hashing with modern algorithms
    - Input sanitization and XSS prevention
13. **[Support Layer](src/TreeHouse/Support/README.md)**

    - Collection class with 50+ utility methods
    - String manipulation and validation utilities
    - Carbon integration for date/time handling
    - Array utilities with dot notation support
14. **[Validation Layer](src/TreeHouse/Validation/README.md)**

    - Comprehensive validation system with 25+ rules
    - Custom validation rule support
    - Conditional validation and nested data handling
    - Internationalized error messages
15. **[View Layer](src/TreeHouse/View/README.md)**

    - Custom template engine with HTML-valid syntax
    - Layout inheritance and component system
    - Template compilation with caching
    - Authentication and authorization integration
16. **[Events Layer](src/TreeHouse/Events/README.md)**

    - **Comprehensive Event System** - Loose coupling architecture
    - **Model Lifecycle Events** - Automatic events with cancellation support
    - **Synchronous Dispatching** - Priority-based event processing
    - **Container Integration** - Automatic dependency injection for listeners

### Advanced Middleware Systems

[](#advanced-middleware-systems)

17. **[Rate Limiting System](src/TreeHouse/Router/Middleware/RateLimit/README.md)**
    - **Multiple Rate Limiting Strategies:**
        - Fixed Window Strategy - Simple time-based windows
        - Sliding Window Strategy - Precise rate limiting without boundary bursts
        - Token Bucket Strategy - Burst-friendly limiting with average rate control
    - **Flexible Key Resolution:**
        - IP-based rate limiting with proxy support
        - User-based rate limiting with authentication integration
        - Header-based rate limiting for API keys
        - Composite rate limiting combining multiple factors
    - **Enterprise Features:**
        - Zero external dependencies
        - Beautiful 429 error pages with debugging info
        - Rate limit headers in all responses
        - Comprehensive test coverage (94 tests, 100% passing)
        - Production-ready performance optimization

> **Detailed Documentation**: Each layer includes comprehensive documentation with examples, API references, and implementation details. Click the layer links above to explore specific functionality.

Features
--------

[](#features)

### Core Framework

[](#core-framework)

- **Zero Dependencies**: Pure PHP implementation with no external libraries
- **Modern PHP 8.4+**: Built for the latest PHP features and type declarations
- **Layered Architecture**: Clean separation of concerns across 16 specialized layers
- **Dependency Injection**: Advanced container with automatic resolution and service registration
- **Configuration Management**: Environment-based configuration with type conversion
- **Extensive Testing**: 1900+ tests with comprehensive coverage

### Authentication &amp; Authorization

[](#authentication--authorization)

- **Multi-Guard Authentication**: Session-based and custom authentication guards
- **Role-Based Access Control (RBAC)**: Complete permission system with roles, permissions, and policies
- **User Providers**: Database and custom user providers with flexible user management
- **Authorization Middleware**: Route-level protection with role and permission checking
- **Template Integration**: Authentication and authorization directives in templates

### JWT Authentication &amp; Authorization (Enterprise-Grade)

[](#jwt-authentication--authorization-enterprise-grade)

- **RFC 7519 Compliance**: Complete JWT standard implementation with zero dependencies
- **Multi-Algorithm Support**: HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, ES512
- **Stateless Authentication**: Perfect for APIs and microservices architecture
- **Multi-Source Token Extraction**: Authorization header (Bearer), cookies, query parameters
- **Claims Management**: Comprehensive JWT claims validation and processing
- **Environment Integration**: Complete .env configuration with production security
- **CLI Tools**: Generate, validate, decode, rotate keys, security audit commands

### HTTP &amp; Routing

[](#http--routing)

- **Flexible Routing**: HTTP routing with middleware support, parameter binding, and route groups
- **Named Routes**: URL generation and route caching for performance
- **Middleware System**: Request/response processing with built-in and custom middleware
- **Request Handling**: Comprehensive HTTP request parsing with file upload support
- **Response Management**: Flexible response building with headers, cookies, and redirects
- **Enterprise Rate Limiting**: Multiple strategies (Fixed Window, Sliding Window, Token Bucket) with flexible key resolution

### Database &amp; ORM

[](#database--orm)

- **ActiveRecord ORM**: Eloquent-style models with relationships and query building
- **Query Builder**: Fluent SQL query construction with method chaining
- **Database Migrations**: Schema management with version control
- **Relationships**: HasOne, HasMany, BelongsTo, and BelongsToMany relationships
- **Connection Management**: Multiple database connections with automatic management

### Template Engine

[](#template-engine)

- **HTML-Valid Syntax**: Custom template engine with `th:` attributes
- **Component System**: Reusable template components with parameter passing
- **Layout Inheritance**: Master layouts with sections and content injection
- **Template Compilation**: Optimized template compilation with caching
- **Authorization Integration**: Built-in auth, role, and permission directives

### Mail System (Complete Implementation)

[](#mail-system-complete-implementation)

- **Multiple Transport Drivers**: SMTP with authentication, Sendmail, Log driver for testing
- **Database Queue System**: Automated email processing with retry logic and performance tracking
- **Laravel-style Mailables**: Easy email composition with TreeHouse template integration
- **File Attachments**: Security validation, MIME type detection, and size limits
- **Event Integration**: Email lifecycle events for monitoring and control
- **Advanced Validation**: Anti-spam features and email address validation
- **CLI Management**: Queue processing, status monitoring, and email generation commands

### Security &amp; Validation

[](#security--validation)

- **CSRF Protection**: Token-based CSRF protection with automatic validation
- **AES-256-CBC Encryption**: Secure encryption/decryption with payload integrity
- **Password Hashing**: Secure password hashing with configurable algorithms
- **Input Sanitization**: XSS protection and data sanitization utilities
- **Comprehensive Validation**: 25+ built-in validation rules with custom rule support
- **JWT Security**: Timing-safe operations, multi-algorithm support, enterprise-grade validation

### Utilities &amp; Support

[](#utilities--support)

- **Array Utilities**: Dot notation support, fluent operations, and data manipulation
- **Collection Class**: Extensive data manipulation with 50+ methods
- **String Utilities**: Case conversion, validation, manipulation, and formatting
- **Date/Time Handling**: Carbon integration with fluent date/time API
- **UUID Generation**: Support for UUID v1, v3, v4, v5 with validation
- **Environment Management**: Type-safe environment variable handling

### Rate Limiting &amp; Traffic Control

[](#rate-limiting--traffic-control)

- **Multiple Rate Limiting Strategies**: Fixed Window, Sliding Window, and Token Bucket algorithms
- **Flexible Key Resolution**: IP-based, user-based, header-based, and composite key generation
- **API Protection**: Protect APIs from abuse with configurable limits per endpoint
- **Burst Traffic Handling**: Token bucket strategy allows controlled burst traffic
- **Rate Limit Headers**: Automatic X-RateLimit-\* headers in responses
- **Beautiful Error Pages**: Comprehensive 429 error pages with debugging information
- **Zero Dependencies**: Pure PHP implementation with no external requirements
- **Production Ready**: Comprehensive test coverage (94 tests, 100% passing)

### Event System &amp; Loose Coupling

[](#event-system--loose-coupling)

- **Event-Driven Architecture**: Comprehensive event system enabling loose coupling between components
- **Model Lifecycle Events**: Automatic events for create, update, delete operations with cancellation support
- **Custom Event Dispatching**: Fire and listen for custom application events
- **Priority-Based Listeners**: Control listener execution order with priority system
- **Container Integration**: Automatic dependency injection for event listeners
- **Performance Optimized**: Listener caching and lazy loading for optimal performance

### Caching &amp; Performance

[](#caching--performance)

- **File-Based Caching**: High-performance file caching with automatic cleanup
- **Prefixed Caching**: Namespace support for cache organization
- **Pattern Matching**: Wildcard-based cache invalidation
- **Cache Statistics**: Performance monitoring and cache analytics

### Console &amp; CLI

[](#console--cli)

- **CLI Application**: Comprehensive command-line interface for development
- **JWT Commands**: Complete JWT management (generate, validate, decode, security audit)
- **User Management**: Create, update, delete users with role assignment
- **Mail Commands**: Queue management, status monitoring, mailable generation
- **Cache Operations**: Cache clearing, statistics, and management
- **Database Operations**: Migration running and database management
- **Development Server**: Built-in development server with hot reloading

Installation
------------

[](#installation)

### Install TreeHouse Globally (Recommended)

[](#install-treehouse-globally-recommended)

Install TreeHouse globally to use the project creation tool:

```
# Install TreeHouse globally
composer global require lengthofrope/treehouse

# Make sure global composer bin is in your PATH
export PATH="$PATH:$HOME/.composer/vendor/bin"

# Create new project using the global treehouse command
treehouse new my-app
cd my-app
treehouse serve
```

### Install as Dependency

[](#install-as-dependency)

```
composer require lengthofrope/treehouse
```

### CLI Tool Overview

[](#cli-tool-overview)

TreeHouse provides a single intelligent CLI command that adapts to your context:

- **`treehouse`** - **Context-Aware CLI Tool**:
    - **Outside TreeHouse projects**: Shows "TreeHouse Project Creator" with only the `new` command for scaffolding projects
    - **Inside TreeHouse projects**: Shows "TreeHouse Project Manager" with all development commands (user management, cache operations, migrations, JWT tools, etc.)

**Note**: The `treehouse` command automatically detects whether you're inside a TreeHouse project directory and shows the appropriate commands. When installed globally, the command is available system-wide. You can also use the local `./bin/treehouse` within projects.

Quick Start
-----------

[](#quick-start)

### 1. Create a Controller with JWT Authentication

[](#1-create-a-controller-with-jwt-authentication)

```
