234 lines
7.9 KiB
Markdown
234 lines
7.9 KiB
Markdown
# Web Framework
|
|
|
|
Web is a lightweight, high-performance PHP web framework built around a hyper-optimized tree-based router. It provides essential web application features with minimal overhead, including routing, middleware, sessions, validation, authentication, and error handling.
|
|
|
|
## Quick Start
|
|
|
|
```php
|
|
<?php
|
|
|
|
namespace Web;
|
|
|
|
require_once 'App.php';
|
|
|
|
$app = new App(debug: true);
|
|
|
|
$app->get('/', function(Context $context) {
|
|
return 'Hello World!';
|
|
});
|
|
|
|
$app->get('/users/:id', function(Context $context, $id) {
|
|
return ['user_id' => $id, 'name' => 'John Doe'];
|
|
});
|
|
|
|
$app->run();
|
|
?>
|
|
```
|
|
|
|
See [EXAMPLES.md](EXAMPLES.md) for comprehensive examples and usage patterns.
|
|
|
|
## Core Components
|
|
|
|
### App (Application)
|
|
The main application class that handles routing, middleware, and request processing.
|
|
- Route registration (`get()`, `post()`, `put()`, `patch()`, `delete()`, `head()`)
|
|
- Middleware support (`use()`)
|
|
- Route grouping (`group()`)
|
|
- Custom error handling (`setErrorHandler()`, `setDefaultErrorHandler()`)
|
|
|
|
### Router
|
|
High-performance tree-based router with dynamic parameter support.
|
|
- Optimized route lookup algorithm
|
|
- Dynamic segments with `:parameter` syntax
|
|
- Returns status codes (200, 404, 405) with matched handlers and parameters
|
|
|
|
### Context
|
|
Central request/response wrapper with helper methods to reduce chaining.
|
|
- Request helpers: `input()` (POST), `query()` (GET), `jsonValue()` (JSON), `param()` (route by index), `all()`
|
|
- Response helpers: `json()`, `text()`, `html()`, `redirect()`, `error()`
|
|
- Request info: `ip()`, `userAgent()`, `header()`, `cookie()`, `expectsJson()`
|
|
- State management: `set()`, `get()`
|
|
- Validation: `validate()`, `validateRequest()`
|
|
|
|
### Request
|
|
Comprehensive HTTP request handling.
|
|
- Explicit input methods: `input()` (POST), `query()` (GET), `jsonValue()` (JSON), `param()` (route by index)
|
|
- Header and cookie access
|
|
- Content type detection
|
|
- URL and security helpers
|
|
|
|
### Response
|
|
HTTP response building with method chaining.
|
|
- Status codes and headers
|
|
- Content types: JSON, HTML, text, redirects
|
|
- Cookie management
|
|
- Manual response building
|
|
|
|
### Session
|
|
Session management with security features.
|
|
- Basic session data storage
|
|
- Flash messages for one-time notifications
|
|
- CSRF token generation and validation
|
|
- Session lifecycle management
|
|
|
|
### Cookies
|
|
Comprehensive cookie management with security features.
|
|
- Consistent cookie handling across the application
|
|
- Convenient lifetime methods (sessions, days, hours, minutes)
|
|
- Signed cookies for integrity verification
|
|
- Encrypted cookies for sensitive data
|
|
- Configurable defaults for all cookie operations
|
|
- Automatic integration with Context and Response
|
|
|
|
### Validator
|
|
Input validation with 20+ built-in rules.
|
|
- Chainable validation rules (`required|email|min:6`)
|
|
- Custom error messages
|
|
- Extensible with custom rules
|
|
- Dot notation support for nested data
|
|
|
|
### Authentication
|
|
User authentication with session and remember token support.
|
|
- Login/logout functionality
|
|
- Password hashing and verification
|
|
- Remember token management
|
|
- External credential verification support
|
|
|
|
### Auth Middleware
|
|
Authentication and authorization middleware.
|
|
- Authentication requirements (`requireAuth()`, `requireGuest()`)
|
|
- Role-based access control (`requireRole()`)
|
|
- Rate limiting (`rateLimit()`)
|
|
- CSRF protection (`verifyCsrf()`)
|
|
|
|
### Error Handling
|
|
Comprehensive error and exception handling.
|
|
- Custom error handlers for specific status codes
|
|
- Debug mode with stack traces
|
|
- Automatic JSON/HTML response formatting
|
|
- Built-in error pages
|
|
|
|
## API Reference
|
|
|
|
### App Class
|
|
```php
|
|
new App(bool $debug = false, array $cookieDefaults = [])
|
|
use(callable $middleware): self
|
|
get|post|put|patch|delete|head(string $route, callable $handler): self
|
|
group(string $prefix, callable $callback): self
|
|
setErrorHandler(int $status, callable $handler): self
|
|
setDefaultErrorHandler(callable $handler): self
|
|
run(): void
|
|
```
|
|
|
|
### Context Class
|
|
```php
|
|
// Request helpers
|
|
input(string $name, mixed $default = null): mixed // POST data
|
|
query(string $name, mixed $default = null): mixed // Query params
|
|
jsonValue(string $name, mixed $default = null): mixed // JSON body
|
|
param(int $index, mixed $default = null): mixed // Route params by index
|
|
all(): array
|
|
only(array $keys): array
|
|
except(array $keys): array
|
|
has(string $key): bool
|
|
header(string $name): ?string
|
|
cookie(string $name): ?string
|
|
ip(): string
|
|
userAgent(): string
|
|
expectsJson(): bool
|
|
isAjax(): bool
|
|
isSecure(): bool
|
|
|
|
// Response helpers
|
|
json(mixed $data, int $status = 200): void
|
|
text(string $text, int $status = 200): void
|
|
html(string $html, int $status = 200): void
|
|
redirect(string $url, int $status = 302): void
|
|
error(int $status, string $message = ''): void
|
|
status(int $code): Response
|
|
setHeader(string $name, string $value): Response
|
|
setCookie(string $name, string $value, array $options = []): Response
|
|
|
|
// State management
|
|
set(string $key, mixed $value): void
|
|
get(string $key): mixed
|
|
|
|
// Validation
|
|
validate(array $data, array $rules, array $messages = []): Validator
|
|
validateRequest(array $rules, array $messages = []): Validator
|
|
```
|
|
|
|
### Validator Rules
|
|
`required`, `email`, `url`, `alpha`, `alphaNum`, `numeric`, `integer`, `float`, `boolean`, `array`, `json`, `date`, `min:n`, `max:n`, `between:min,max`, `length:n`, `in:a,b,c`, `notIn:a,b,c`, `regex:/pattern/`, `confirmed`, `unique:table,column`, `exists:table,column`
|
|
|
|
### Cookies Class
|
|
```php
|
|
new Cookies(array $defaults = [])
|
|
set(string $name, string $value, array $options = []): bool
|
|
get(string $name, ?string $default = null): ?string
|
|
has(string $name): bool
|
|
delete(string $name, array $options = []): bool
|
|
setSession(string $name, string $value, array $options = []): bool
|
|
setWithLifetime(string $name, string $value, int $lifetime, array $options = []): bool
|
|
setForDays(string $name, string $value, int $days, array $options = []): bool
|
|
setForHours(string $name, string $value, int $hours, array $options = []): bool
|
|
setForMinutes(string $name, string $value, int $minutes, array $options = []): bool
|
|
forever(string $name, string $value, array $options = []): bool
|
|
all(): array
|
|
clear(): void
|
|
setSigned(string $name, string $value, string $secret, array $options = []): bool
|
|
getSigned(string $name, string $secret, ?string $default = null): ?string
|
|
setEncrypted(string $name, string $value, string $key, array $options = []): bool
|
|
getEncrypted(string $name, string $key, ?string $default = null): ?string
|
|
```
|
|
|
|
### Auth Class
|
|
```php
|
|
new Auth(Session $session, ?Cookies $cookies = null, array $config = [])
|
|
login(array $userData, bool $remember = false): void
|
|
logout(): void
|
|
check(): bool
|
|
guest(): bool
|
|
user(): ?User
|
|
id(): int|string|null
|
|
hashPassword(string $password): string
|
|
verifyPassword(string $password, string $hash): bool
|
|
```
|
|
|
|
### AuthMiddleware Methods
|
|
```php
|
|
requireAuth(): callable
|
|
requireGuest(): callable
|
|
optional(): callable
|
|
requireRole(string|array $roles): callable
|
|
rateLimit(int $maxAttempts = 60, int $decayMinutes = 1): callable
|
|
verifyCsrf(): callable
|
|
```
|
|
|
|
## Features
|
|
|
|
- **High Performance**: Tree-based router with O(1) lookup complexity
|
|
- **Minimal Overhead**: Lightweight design with essential features only
|
|
- **Method Chaining**: Fluent API for response building
|
|
- **Middleware Support**: Pre/post request processing
|
|
- **Route Groups**: Organize routes with shared prefixes and middleware
|
|
- **Input Validation**: Comprehensive validation with built-in rules
|
|
- **Authentication**: Session-based auth with remember tokens
|
|
- **Error Handling**: Custom error pages with debug support
|
|
- **CSRF Protection**: Built-in CSRF token generation and validation
|
|
- **Flash Messages**: One-time notifications between requests
|
|
- **Rate Limiting**: Configurable rate limiting per user/IP
|
|
- **Content Negotiation**: Automatic JSON/HTML response selection
|
|
|
|
## Documentation
|
|
|
|
- **[EXAMPLES.md](EXAMPLES.md)** - Comprehensive examples and usage patterns
|
|
- **API Reference** - Complete method documentation (above)
|
|
- **Source Code** - Well-documented PHP classes
|
|
|
|
## Requirements
|
|
|
|
- PHP 8.1+ (uses enums and modern syntax)
|
|
- No external dependencies
|
|
- Works with any PHP web server |