DEV Community

Yasser Elgammal
Yasser Elgammal

Posted on

Green Framework v2: Modern PHP Framework for Web Development

Green Framework is a modern and lightweight PHP framework designed to make building web applications and APIs simpler, faster, and more predictable.

Green focuses on clean architecture, explicit code, and modern PHP features without adding unnecessary complexity.

Instead of hiding what happens behind the scenes, Green aims to give developers a clear understanding of how their application works.

🚀 Why Green?

Green provides the essential tools you need to build modern PHP applications while keeping the framework lightweight and easy to understand.

✨ Modern PHP

Green takes advantage of modern PHP features such as Attributes, Reflection, Type Declarations, and modern object-oriented architecture.

For example, routes can be defined directly inside controllers:

#[Route('GET', '/users/{id}', name: 'users.show')]
public function show(int $id): array
{
    return [
        'id' => $id,
    ];
}
Enter fullscreen mode Exit fullscreen mode

No separate route file is required for simple controller-based routing.

🛣️ Powerful Routing

Green provides an attribute-based routing system powered by FastRoute.

You can define:

  • HTTP methods
  • Route parameters
  • Named routes
  • Route middleware
  • Authorization policies

Named routes can also be used to generate URLs:

route('users.show', ['id' => 5]);
Enter fullscreen mode Exit fullscreen mode

This keeps your application routing organized and avoids hardcoding URLs throughout your application.

🧩 Lightweight Service Container

Green includes a lightweight Service Container with:

  • Dependency injection
  • Auto-wiring
  • Bindings
  • Singletons
  • Explicit instances
  • Circular dependency detection

For example:

class UserService
{
    public function __construct(
        private UserTable $users
    ) {}
}
Enter fullscreen mode Exit fullscreen mode

Dependencies can be resolved automatically through PHP Reflection while still keeping the container simple and predictable.

⚙️ Centralized Configuration

Green includes a centralized configuration system designed to provide a single, immutable configuration snapshot for the application.

Configuration can come from:

  • Framework defaults
  • Environment variables
  • config/*.php
  • Application overrides
  • Cached configuration

For production environments, configuration can also be cached:

green config:cache
Enter fullscreen mode Exit fullscreen mode

Green also provides:

green config:show
green config:clear
Enter fullscreen mode Exit fullscreen mode

Sensitive values such as passwords, tokens, and API keys are automatically redacted when configuration is displayed.

🗄️ Database & ORM

One of Green's main architectural decisions is its database layer.

Instead of putting database logic directly inside models, Green separates data from persistence.

Table Gateway & Data Mapper

The Model represents your data, while the Table handles database operations.

Model
  ↓
Data

Table
  ↓
Database Operations
Enter fullscreen mode Exit fullscreen mode

This approach is based on the Table Gateway and Data Mapper patterns and keeps models free from database logic.

🔎 Fluent Query Builder

Green provides a simple fluent query layer through GreenQuery.

$users = $userTable->query()
    ->where('status', 'active')
    ->whereGroup(fn ($query) => $query
        ->where('role', 'admin')
        ->orWhere('score', '>=', 90)
    )
    ->latest()
    ->fetch();
Enter fullscreen mode Exit fullscreen mode

It supports:

  • where
  • orWhere
  • Grouped conditions
  • Ordering
  • Pagination
  • Aggregates
  • exists
  • first
  • Limits and offsets

The query layer is built on top of Doctrine DBAL while keeping Green's API simple.

🔗 Relations & Eager Loading

Green includes a relation engine supporting:

  • hasOne
  • hasMany
  • belongsTo
  • manyToMany

Relations can be loaded using:

$userTable->include('posts');
Enter fullscreen mode Exit fullscreen mode

Nested relations are supported as well:

$userTable->include('posts.comments');
Enter fullscreen mode Exit fullscreen mode

Green's eager-loading system is designed to avoid the N+1 query problem by loading related records using optimized WHERE IN (...) queries and stitching the results together in memory.

🧠 Include Query Language — IQL

For APIs that need dynamic eager loading, Green introduces IQL — Include Query Language.

For example:

comments(limit:5,order:desc).author(select:id|name)
Enter fullscreen mode Exit fullscreen mode

This allows API consumers to describe which relations they want and how those relations should be loaded.

Green parses, validates, and resolves the query before applying it to the underlying database query.

✅ Validation

Green provides a Payload system for handling validated request data.

A Payload can handle:

  • Data preparation
  • Authorization
  • Validation
  • Structured validation errors

For example:

class CreateUserPayload extends Payload
{
    public function rules(): array
    {
        return [
            'email' => v::email(),
            'name' => v::stringType()->notEmpty(),
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Validation errors are automatically converted into appropriate HTTP responses.

🛡️ Authorization

Green provides an explicit authorization system based on Policies and an Authorizer.

You can protect controller actions using Attributes:

#[PolicyAttribute('update', 'post')]
public function edit(int $id)
{
    //
}
Enter fullscreen mode Exit fullscreen mode

This keeps authorization rules separate from business logic and makes permissions easier to understand.

🔐 Built-in CSRF Protection

Green includes CSRF protection for state-changing HTTP requests.

It provides:

  • Cryptographically secure tokens
  • Timing-safe validation
  • Single-use tokens
  • Token expiration
  • Configurable token limits
  • Configurable exception paths

Tokens can be generated for forms and validated automatically through middleware.

🚨 Error & Exception Handling

Green includes a centralized error-handling system capable of handling:

  • Exceptions
  • PHP errors
  • Fatal errors
  • Structured error records
  • Logging
  • Error deduplication
  • Rate limiting

Errors can be returned as either JSON or HTML, depending on the request.

Stack traces are only exposed when debug mode is enabled.

This helps keep production applications safer while still providing useful debugging information during development.

🌍 Localization

Green includes a localization engine with support for:

  • JSON translation files
  • Database translations
  • Locale fallback
  • Variable interpolation
  • Pluralization
  • Arabic plural rules

For example:

t('messages.welcome');
Enter fullscreen mode Exit fullscreen mode

The translation system supports locale fallback such as:

ar_EG
  ↓
ar
  ↓
fallback locale
  ↓
default locale
Enter fullscreen mode Exit fullscreen mode

Green also provides first-class support for Arabic localization.

📁 Drive Storage

Green provides a filesystem abstraction called Drive.

It supports operations such as:

drive()->put(...)
drive()->get(...)
drive()->delete(...)
drive()->exists(...)
Enter fullscreen mode Exit fullscreen mode

The storage system supports multiple drivers and can be extended with custom drivers.

It also includes security protections against:

  • Directory traversal
  • Null-byte injection
  • Invalid control characters
  • Root escape through symlinks

Testing storage operations is also possible through an in-memory fake driver.

⚡ Cache

Green provides a cache abstraction supporting multiple drivers, including:

  • File
  • Array
  • Database
  • Redis

You can use the remember() pattern to retrieve or calculate cached values:

cache()->remember('users', 3600, function () {
    return getUsers();
});
Enter fullscreen mode Exit fullscreen mode

This keeps caching logic independent from the underlying storage implementation.

📡 Signals — Event System

Green includes a lightweight event system called Signals.

Listeners can subscribe using Attributes:

#[Signal('user.registered')]
public function handle(UserRegistered $event)
{
    //
}
Enter fullscreen mode Exit fullscreen mode

Events can be dispatched simply:

dispatch('user.registered', $user);
Enter fullscreen mode Exit fullscreen mode

This provides a clean way to decouple application components and react to domain events.

🌐 External API Integrations

Green includes the Connect subsystem for consuming external HTTP APIs.

It is built on top of Guzzle and encourages keeping API communication inside dedicated service objects.

This helps keep external API logic isolated from controllers and business logic.

🧱 Middleware Pipeline

Green uses an Onion-style middleware pipeline.

A request moves through middleware before reaching the controller and then travels back through the same pipeline when a response is returned.

Request
   ↓
Middleware
   ↓
Middleware
   ↓
Controller
   ↓
Response
   ↓
Middleware
   ↓
Middleware
Enter fullscreen mode Exit fullscreen mode

This makes authentication, authorization, logging, CORS, CSRF, and other request-level concerns easier to organize.

🎯 Explicit by Design

Green follows a few simple principles:

  • Explicit over Magic
  • Minimal Core
  • Predictable Runtime Behavior
  • Clean Separation of Responsibilities
  • Extensible Architecture
  • Modern PHP
  • Low Unnecessary Complexity

The goal is not to replace every tool in the PHP ecosystem.

The goal is to provide a clean foundation that gives developers the tools they need without forcing them into unnecessary abstractions.

⚡ Installation

You can create a new Green Framework project using Composer:

composer create-project yasser-elgammal/green app-name
Enter fullscreen mode Exit fullscreen mode

Then start building your application using modern PHP and Green's lightweight architecture.

📚 Documentation & Source Code

The Green Framework documentation and source code are available on GitHub.

You can explore the architecture, read the documentation, open issues, suggest improvements, or contribute to the project.

💚 Conclusion

Green Framework v2 has grown from a simple PHP framework into a modern foundation for building web applications and APIs.

It combines:

  • Modern PHP
  • Attribute-based routing
  • Dependency injection
  • Centralized configuration
  • Validation
  • Authorization
  • CSRF protection
  • Localization
  • Storage
  • Caching
  • Events
  • API integrations
  • Table Gateway ORM
  • Fluent queries
  • Relations and eager loading
  • Advanced Include Queries
  • Centralized error handling

while keeping its original philosophy:

Build with less magic. Understand more.

Green is for developers who want a framework that helps them move fast without making the code harder to understand.

Top comments (0)