Download the PHP package quellabs/canvas without Composer
On this page you can find all versions of the php package quellabs/canvas. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download quellabs/canvas
More information about quellabs/canvas
Files in quellabs/canvas
Package canvas
Short Description A modern, lightweight PHP framework with contextual containers, automatic service discovery, and ObjectQuel ORM integration
License MIT
Informations about the package canvas
Canvas
Canvas is a lightweight, modern PHP framework built for real-world projects. Whether you're starting fresh or modernizing legacy code, Canvas offers a clean architecture with annotation-based routing, contextual dependency injection, and an intuitive ORM. No magic, no bloat โ just the tools you actually need.
๐ง Key Features
- ๐งฉ Legacy-First Integration โ Drop into existing PHP projects without rewriting routes or structure
- ๐ Annotation-Based Routing โ Define clean, intuitive routes directly on controller methods
- ๐ฆ Contextual Dependency Injection โ Use interfaces; Canvas resolves the right implementation per context
- ๐๏ธ ObjectQuel ORM โ Query your database with a readable, PHP-native syntax inspired by QUEL
- โ๏ธ Aspect-Oriented Programming โ Add behaviors like validation, CSRF, and caching via reusable aspects
- ๐ Event-Driven Signals โ Decoupled service communication with Qt-style signal/slot architecture
- โฐ Task Scheduling โ Cron-style background jobs with timeouts and safe concurrent handling
- ๐งผ Validation & Sanitization โ Clean and verify request data using declarative rules and aspects
- ๐ Secure by Default โ Built-in CSRF protection, security headers, and input hardening
- ๐ Powerful Inspector โ Visual debugging interface with database queries, request analysis, and custom panels
- ๐ง No Magic โ Everything is explicit, traceable, and designed for developers who like control
Quick Start
Installation
Bootstrap (public/index.php)
This bootstrap file is automatically generated when using the skeleton package. If you're not using the skeleton package, you'll need to create this file manually.
Controllers with Route Annotations
Canvas automatically discovers controllers and registers their routes using annotations:
ObjectQuel ORM
ObjectQuel lets you query data using syntax that feels natural to PHP developers. Inspired by QUEL (a declarative query language from early relational databases), it bridges traditional database querying with object-oriented programming.
Simple Entity Operations
Advanced ObjectQuel Queries
For complex queries, ObjectQuel provides a natural language syntax:
Key Components
range
- Creates an alias for an entity class, similar to SQL'sFROM
clause. Think of it as "let p represent App\Entity\Post"retrieve
- Functions like SQL'sSELECT
, specifying what data to return. You can retrieve entire entities (p
) or specific properties (u.name
)where
- Standard filtering conditions, supporting parameters (:published
) and regular expressions (/^Tech/i
matches titles starting with "Tech", case-insensitive)sort by
- Equivalent to SQL'sORDER BY
for result orderingvia
- Establishes relationships between entities using foreign keys (p.authorId
links posts to users)
ObjectQuel Features
- Readability: More intuitive than complex Doctrine DQL or QueryBuilder syntax
- Type Safety: Entity relationships are validated at query time
- Parameter Binding: Safe parameter substitution prevents SQL injection
- Relationship Traversal: Easily query across entity relationships with
via
keyword - Flexible Sorting: Multi-column sorting with
sort by field1 asc, field2 desc
Route Validation & Parameters
Canvas provides powerful route parameter validation to ensure your controllers receive the correct data types and formats.
Basic Parameter Validation
Advanced Parameter Patterns
Available Validators
int
- Integer numbers onlyalpha
- Alphabetic characters onlyalnum
- Alphanumeric characters onlyslug
- URL-friendly slugs (letters, numbers, hyphens)uuid
- Valid UUID formatemail
- Valid email address format- ``** - Wildcard (matches any characters including slashes)
Route Prefixes
Group related routes under a common prefix:
Method Constraints
Restrict routes to specific HTTP methods:
Form Validation
Canvas provides a powerful validation system that separates validation logic from your controllers using aspects, keeping your business logic clean and focused.
Basic Form Validation
Creating Validation Classes
Define your validation rules in dedicated classes:
Available Validation Rules
Canvas includes common validation rules out of the box:
AtLeastOneOf
- At least one field from a group must be filledDate
- Valid date format validationEmail
- Valid email formatLength
- String length constraints (min
,max
)NotBlank
- Field cannot be emptyNotHTML
- Field cannot contain HTML tagsPhoneNumber
- Valid phone number formatRegExp
- Custom regular expression matchingType
- Type validation (string, integer, array, etc.)ValueIn
- Value must be from a predefined listZipcode
- Valid zipcode/postal code formatNotLongWord
- Prevents excessively long words
API Validation with Auto-Response
For API endpoints, enable automatic JSON error responses. When auto_respond=true
, the validation aspect will automatically return error responses when validation fails, so you don't need to check validation results in your controller method:
Custom Validation Rules
Create your own validation rules by implementing the ValidationRuleInterface
:
Use custom rules in your validation classes:
Input Sanitization
Canvas provides a powerful input sanitization system that automatically cleans and normalizes incoming request data before it reaches your controllers. The sanitization system works seamlessly with Canvas's validation system to provide a complete input security layer.
Why Sanitize Input?
Input sanitization is crucial for:
- XSS Prevention - Remove or neutralize potentially dangerous HTML/JavaScript
- Data Normalization - Ensure consistent data formats (emails, phone numbers, etc.)
- Content Filtering - Strip unwanted characters or content
- Security Hardening - Clean data before validation and processing
Basic Sanitization
Apply sanitization using the @InterceptWith
annotation with SanitizeAspect
:
Creating Sanitization Classes
Define your sanitization rules in dedicated classes that implement SanitizationInterface
:
Built-in Sanitization Rules
Canvas includes essential sanitization rules focused on security and data cleaning:
Text Sanitization
Trim
- Remove leading and trailing whitespaceStripTags
- Remove HTML tags (with optional allowlist for safe tags)
Security Sanitization
ScriptSafe
- Remove or neutralize dangerous script-related contentSqlSafe
- Remove characters commonly used in SQL injection attemptsNormalizeLineEndings
- Converts all line ending to a consistent Unix-style LF formatRemoveControlChars
- Remove control characters that can cause display issuesRemoveNullBytes
- Removes null bytes (0x00) to prevent null byte injection attacksRemoveZeroWidth
- Removes invisible Unicode charactersRemoveStyleAttributes
- Removes all style attributes from HTML elements
URL and Path Sanitization
EmailSafe
- Remove characters not allowed in email addressesUrlSafe
- Remove characters not safe for URLsPathSafe
- Remove characters not safe for file paths (prevents directory traversal)
Combining Sanitization with Validation
Sanitization works best when combined with validation. The order depends on your specific needs:
Chain Sanitization
Apply multiple sanitization rules to the same field. Rules are executed in the order they're defined:
Custom Sanitization Rules
Create your own sanitization rules by implementing SanitizationRuleInterface
. Here are examples of non-destructive sanitization:
Performance Considerations
- Selective Sanitization - Only define rules for fields that need sanitization
- Efficient Rules - Custom rules should be optimized for performance
- Type Checking - Rules should check input types before processing
Error Handling
Sanitization is designed to be non-breaking. Invalid sanitization classes or rules will throw descriptive exceptions:
Built-in Aspects
Canvas includes three powerful built-in aspects that handle common web application concerns. These aspects demonstrate the framework's commitment to security, performance, and best practices.
CSRF Protection Aspect
The CsrfProtectionAspect
implements Cross-Site Request Forgery protection using tokens to ensure requests originate from your application.
Features
- Automatic Token Generation - Creates unique tokens for each user session
- Smart Validation - Checks tokens in both form data and headers (for AJAX requests)
- Safe Method Exemption - Skips protection for GET, HEAD, and OPTIONS requests
- Session Management - Prevents session bloat with configurable token limits
- Flexible Response Handling - Returns appropriate error formats for web and API requests
Basic Usage
Template Integration
Use the CSRF token in your forms:
AJAX Integration
For AJAX requests, include the token in headers:
Configuration Options
Customize CSRF protection behavior:
Parameters:
tokenName
- Form field name for the token (default:_csrf_token
)headerName
- HTTP header name for AJAX tokens (default:X-CSRF-Token
)intention
- Token scope/purpose for different contexts (default:default
)exemptMethods
- HTTP methods that skip validation (default:['GET', 'HEAD', 'OPTIONS']
)maxTokens
- Maximum tokens per intention to prevent session bloat (default:10
)
Security Headers Aspect
The SecurityHeadersAspect
automatically adds security-related HTTP headers to protect against common web vulnerabilities following OWASP recommendations.
Protected Attacks
- Clickjacking - X-Frame-Options prevents embedding in malicious frames
- MIME Sniffing - X-Content-Type-Options prevents content type confusion
- XSS - X-XSS-Protection enables browser XSS filtering
- Man-in-the-Middle - Strict-Transport-Security enforces HTTPS
- Information Leakage - Referrer-Policy controls referrer information
- Code Injection - Content-Security-Policy prevents unauthorized script execution
Basic Usage
Configuration Options
Customize security headers for different needs:
Parameters:
frameOptions
- X-Frame-Options value:DENY
,SAMEORIGIN
, orALLOW-FROM
(default:SAMEORIGIN
)noSniff
- Enable X-Content-Type-Options: nosniff (default:true
)xssProtection
- Enable X-XSS-Protection (default:true
)hstsMaxAge
- HSTS max-age in seconds, 0 disables (default:31536000
= 1 year)hstsIncludeSubdomains
- Include subdomains in HSTS (default:true
)referrerPolicy
- Referrer-Policy value (default:strict-origin-when-cross-origin
)csp
- Content-Security-Policy value, null disables (default:null
)
Content Security Policy Examples
Common CSP configurations for different application types:
Cache Aspect
The CacheAspect
provides method-level caching with intelligent key generation, configurable TTL, and thread-safe operations.
Features
- Automatic Key Generation - Creates cache keys from method signature and arguments
- Thread-Safe Operations - Uses file locking to prevent cache corruption
- Graceful Fallback - Executes original method if caching fails
- Flexible TTL - Configurable time-to-live with never-expire option
- Context Namespacing - Separate cache contexts for different application areas
- Argument-Aware - Different cache entries for different method arguments
Basic Usage
Custom Cache Keys
Override automatic key generation:
Configuration Options
Parameters:
key
- Custom cache key template, null for auto-generation (default:null
)ttl
- Time to live in seconds, 0 for never expires (default:3600
)namespace
- Cache namespace for organization (default:default
)lockTimeout
- File lock timeout in seconds (default:5
)gracefulFallback
- Execute method if caching fails (default:true
)
Cache Key Generation
The aspect automatically generates intelligent cache keys:
Performance Considerations
- Argument Serialization - Complex objects are hashed to keep keys manageable
- Key Length Limits - Long keys are automatically truncated and hashed
- Lock Timeouts - Configurable timeouts prevent indefinite blocking
- Storage Efficiency - File-based storage with automatic cleanup
Inspector
Canvas includes a powerful visual inspector that appears at the bottom of your web pages during development. It provides essential insights into your application's performance, database queries, request data, and more.
Enabling the Inspector
The inspector is controlled by your application configuration:
Important: The inspector only appears on HTML responses.
Built-in Debug Panels
Canvas ships with essential debug panels that provide immediate value:
Request Panel ๐
Displays comprehensive request information:
- Route Information: Controller, method, route pattern, and parameters
- Request Details: HTTP method, URI, IP address, user agent
- POST Data: Form submissions and request body content
- File Uploads: Details about uploaded files including validation status
- Cookies: All cookies sent with the request
Database Panel ๐๏ธ
Shows database query analysis:
- Query List: All executed database queries with syntax highlighting
- Performance Metrics: Execution time for each query with color-coded performance indicators
- Parameter Binding: Bound parameters for each query to help debug issues
- Total Statistics: Overall query count and cumulative execution time
Inspector Features
Performance Statistics
The inspector header shows key performance metrics at a glance:
- Execution Time: Total request processing time
- Query Count: Number of database queries executed
- Query Time: Total time spent on database operations
Interactive Interface
- Minimizable: Click the header to expand/collapse the inspector
- Tabbed Navigation: Switch between different debug panels
- Remain Open: Checkbox to keep the inspector expanded across page loads
- Responsive Design: Works well on desktop and mobile screens
Smart HTML Injection
The inspector intelligently injects itself into your HTML responses:
- Optimal Placement: Automatically finds the best location (before
</body>
) - Fallback Strategies: Works even with malformed HTML
- Safe Injection: Won't break existing page functionality
Creating Custom Debug Panels
Extend the inspector with custom panels for your specific debugging needs:
Registering Custom Panels
Configure custom panels in your application config:
Debug Event System
The inspector uses Canvas's signal system to collect debugging information:
Emitting Debug Events
Emit debug events from your services:
Common Debug Signals
Canvas uses standardized signal patterns:
debug.database.query
- Database queries with performance datadebug.canvas.query
- Route and controller execution informationdebug.cache.*
- Cache operations (hits, misses, writes)debug.security.*
- Security-related events (CSRF, authentication)debug.validation.*
- Form validation results
JavaScript API
The inspector provides a client-side JavaScript API for advanced interactions:
Best Practices
Development Workflow
- Enable inspector during development for immediate feedback
- Monitor query counts to identify N+1 problems
- Check execution times for performance bottlenecks
- Review request data to debug form submissions and routing issues
Security Considerations
- Never enable inspector in production environments
- Sensitive data is automatically sanitized in panel displays
- Debug events are memory-only and not persisted
Troubleshooting
Inspector Not Appearing
Check these common issues:
- Ensure
enabled
is set totrue
in config/inspector.php - Verify the response is HTML (debug bar only works with HTML responses)
- Check that the response contains a closing
</body>
or</html>
tag - Ensure no JavaScript errors are preventing the bar from initializing
Performance Impact
The inspector is designed for development use:
- Development: Minimal impact, designed for real-time debugging
- Production: Zero impact when disabled
- Memory Usage: Events are stored in memory only during request processing
Task Scheduling
Canvas includes a comprehensive task scheduling system that allows you to run background jobs on a cron-like schedule. The scheduler supports multiple execution strategies, timeout handling, and distributed locking to prevent concurrent task execution.
Creating Tasks
Create tasks by extending the AbstractTask
class and implementing the required methods:
Task Discovery
Canvas automatically discovers tasks using its own discovery mechanism that reads from composer.json
. Add your task classes to your composer.json
:
After updating composer.json, run:
Running the Task Scheduler
Running the task scheduler is done through sculpt:
Setting Up Cron
Add this to your system's crontab to run the scheduler every minute:
Cron Schedule Format
Canvas uses standard cron expressions for scheduling:
Common Examples:
Timeout Strategies
Canvas automatically selects the best timeout strategy based on your system:
- No Timeout Strategy: Used when
getTimeout()
returns 0 - PCNTL Strategy (Preferred): Used on systems with PCNTL support. Uses signals for efficient timeout handling
- Process Strategy (Fallback): Used on systems without PCNTL. Runs tasks in separate processes:
Event-Driven Architecture with SignalHub
Canvas includes a signal system inspired by Qt's signals and slots pattern, enabling components to communicate without tight coupling.
Basic Signal Usage
Add the HasSignals
trait to emit signals from your classes:
Connecting to Signals
Listen for signals in other services:
Using Standalone Signals
Create global signals with SignalHub:
Controller Integration
Use signals in controllers with dependency injection:
Key Features
- Type Safety: Parameters are validated when connecting and emitting
- Simple Setup: Just add the
HasSignals
trait to start emitting signals - Flexible Connections: Connect using object methods or anonymous functions
- Dependency Injection: Works seamlessly with Canvas's container system
Legacy Integration
Canvas is designed to work seamlessly alongside existing PHP codebases, allowing you to modernize your applications incrementally without breaking existing functionality. The legacy integration system provides a smooth migration path from traditional PHP applications to Canvas.
Quick Start with Legacy Code
Start using Canvas today in your existing PHP application. No rewrites required - Canvas's intelligent fallthrough system lets you modernize at your own pace.
First, enable legacy support by updating your public/index.php
:
That's it! Your existing application now has Canvas superpowers while everything continues to work exactly as before.
Using Canvas Services in Legacy Files
Now you can immediately start using Canvas services in your existing files:
How Route Fallthrough Works
Canvas uses an intelligent fallthrough system that tries Canvas routes first, then automatically looks for corresponding legacy PHP files:
Custom File Resolvers
If your legacy application has a different file structure, you can write custom file resolvers:
Legacy Preprocessing
Canvas includes preprocessing capabilities to handle legacy PHP files that use common patterns like header()
,
die()
, and exit()
functions. It also rewrites mysqli and pdo queries for automatic performance measuring in
the inspector.
What preprocessing does:
- Converts
header()
calls to Canvas's internal header management - Transforms
http_response_code()
to Canvas response handling - Converts
die()
andexit()
calls to Canvas exceptions (maintains flow control) - Converts
mysqli_query()
andmysqli_prepare()
calls to internal versions for performance measuring - Converts
pdo
calls to internal versions for performance measuring
Benefits of Legacy Integration
- ๐ Zero Disruption: Existing URLs continue to work unchanged
- ๐ง Enhanced Legacy Code: Add Canvas services (ORM, caching, logging) to legacy files
- ๐ Flexible Migration: Start with services, move to controllers, then to full Canvas
- ๐ Immediate Benefits: Better database abstraction, modern dependency injection, improved error handling
Advanced Features
Aspect-Oriented Programming
Canvas provides true AOP for controller methods, allowing you to separate crosscutting concerns from your business logic. Aspects execute at different stages of the request lifecycle.
Creating Aspects
Aspects implement interfaces based on when they should execute:
Applying Aspects
Class-level aspects apply to all methods in the controller:
Method-level aspects apply to specific methods:
Aspect Parameters
Pass configuration to aspects through annotation parameters:
The aspect receives these as constructor parameters:
Execution Order
Aspects execute in a predictable order:
- Before Aspects - Authentication, validation, rate limiting
- Around Aspects - Caching, transactions, timing
- After Aspects - Logging, response modification
Inherited Aspects
Build controller hierarchies with shared crosscutting concerns:
Contextual Services
Use different implementations based on context:
CLI Commands
Canvas includes a command-line interface called Sculpt for managing your application:
Route Management
Task Scheduler Management
Asset Publishing
Canvas provides a powerful asset publishing system to deploy configuration files, templates, and other resources:
Why Canvas?
- Legacy Integration: Works with existing PHP without breaking anything
- Zero Config: Start coding immediately with sensible defaults
- Clean Code: Annotations keep logic close to implementation
- Performance: Lazy loading, route caching, efficient matching
- Flexibility: Contextual containers and composable aspects
- Event-Driven: Decoupled components with type-safe signal system
- Task Scheduling: Robust background job processing with multiple execution strategies
- Powerful Debugging: Visual debug bar with database queries, request analysis, and extensible panels
- Growth: Scales from simple sites to complex applications
Contributing
We welcome contributions! Here's how you can help improve Canvas:
Reporting Issues
- Use GitHub issues for bug reports and feature requests
- Include minimal reproduction cases
- Specify Canvas version and PHP version
Contributing Code
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature
- Follow PSR-12 coding standards
- Add tests for new functionality
- Update documentation for new features
- Submit a pull request
License
Canvas is open-sourced software licensed under the MIT license.
All versions of canvas with dependencies
ext-mysqli Version *
ext-pdo Version *
ext-curl Version *
ext-gd Version *
ext-fileinfo Version *
monolog/monolog Version *
quellabs/contracts Version ^1.
quellabs/support Version ^1.
quellabs/discover Version ^1.
quellabs/dependency-injection Version ^1.
quellabs/sculpt Version ^1.
quellabs/cache Version ^1.
quellabs/signal-hub Version ^1.
quellabs/canvas-smarty Version ^1.
quellabs/annotation-reader Version ^1.
symfony/http-foundation Version *
dragonmantank/cron-expression Version *