Download the PHP package neuron-php/mvc without Composer
On this page you can find all versions of the php package neuron-php/mvc. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package mvc
Neuron-PHP MVC
A lightweight MVC (Model-View-Controller) framework component for PHP 8.4+ that provides core MVC functionality including controllers, views, routing integration, request handling, and a powerful view caching system.
Table of Contents
- Installation
- Quick Start
- Core Components
- Configuration
- Usage Examples
- Advanced Features
- CLI Commands
- API Reference
- Testing
- More Information
Installation
Requirements
- PHP 8.4 or higher
- Composer
Install via Composer
Install php composer from https://getcomposer.org/
Install the neuron MVC component:
Quick Start
1. Create the Front Controller
Create a public/index.php file:
2. Configure Apache (.htaccess)
Create a public/.htaccess file to route all requests through the front controller:
For Nginx
If using Nginx, add this to your server configuration:
3. Minimal Configuration
Create a config/neuron.yaml file:
Core Components
Application
The main application class (Neuron\Mvc\Application) handles:
- Route discovery from controller attributes
- Request routing and controller execution
- Event dispatching for HTTP errors
- Output capture for testing
- Cache management
Controllers
Controllers handle incoming requests and return responses. All controllers should extend Neuron\Mvc\Controllers\Base and implement the IController interface.
Available render methods:
renderHtml()- Render HTML views with layoutsrenderJson()- Return JSON responsesrenderXml()- Return XML responsesrenderMarkdown()- Render Markdown content with CommonMark
Views
Views support multiple formats and are stored in the configured views directory:
HTML Views
Layouts
Routing
Routes are defined using PHP attributes on controller methods:
Request Handling
Create request DTO definitions for validation. You can define DTOs inline or reference external DTO files:
Inline DTO Definition:
Referenced DTO:
Access validated data in controllers:
URL Helpers
The framework provides Rails-style URL helpers for generating URLs from named routes. This makes it easy to generate consistent URLs throughout your application.
Route Naming
Routes are automatically named based on their configuration key in the YAML file:
Using URL Helpers in Controllers
Controllers can use URL helpers directly via magic methods:
Direct URL Helper Methods
Controllers also provide direct helper methods:
Using URL Helpers in Views
URL helpers are automatically available in all views through the injected $urlHelper variable:
Magic Method Conventions
The magic methods follow Rails naming conventions:
| Route Name in YAML | Magic Method (Relative) | Magic Method (Absolute) | Generated URL |
|---|---|---|---|
user_profile |
userProfilePath() |
userProfileUrl() |
/users/123 |
user_edit |
userEditPath() |
userEditUrl() |
/users/123/edit |
admin_user_posts |
adminUserPostsPath() |
adminUserPostsUrl() |
/admin/users/1/posts/2 |
blog_category |
blogCategoryPath() |
blogCategoryUrl() |
/blog/category/tech |
URL Helper Methods
| Method | Description | Example |
|---|---|---|
routePath($name, $params) |
Generate relative URL | $urlHelper->routePath('user_profile', ['id' => 123]) |
routeUrl($name, $params) |
Generate absolute URL | $urlHelper->routeUrl('user_profile', ['id' => 123]) |
routeExists($name) |
Check if route exists | $urlHelper->routeExists('user_profile') |
getAvailableRoutes() |
List all named routes | $urlHelper->getAvailableRoutes() |
{routeName}Path($params) |
Magic method for relative URL | $urlHelper->userProfilePath(['id' => 123]) |
{routeName}Url($params) |
Magic method for absolute URL | $urlHelper->userProfileUrl(['id' => 123]) |
Error Handling
URL helpers gracefully handle missing routes:
Advanced Usage
Configuration
All YAML config file parameters can be overridden by environment variables in the form of <CATEGORY>_<KEY>, e.g.
SYSTEM_BASE_PATH.
Main Configuration (neuron.yaml)
Routing Configuration (routing.yaml)
Routing configuration is now handled in a dedicated config/routing.yaml file. This separates routing concerns from the main application configuration.
Key Features:
-
URL Rewrites: Transparently rewrite URLs before route matching
- No HTTP redirects (faster, invisible to client)
- Override package-provided routes
- Support legacy URLs without duplicate routes
- Controller Paths: Specify where to scan for route attributes
- Order matters: first paths take precedence
- Allows overriding routes from packages
Backward Compatibility:
For backward compatibility, controller_paths can still be configured in neuron.yaml:
If both files exist, routing.yaml takes precedence.
Cache Configuration Options
| Option | Description | Default |
|---|---|---|
enabled |
Enable/disable caching globally | true |
storage |
Storage type (currently only 'file') | file |
path |
Directory for cache files | cache/views |
ttl |
Default time-to-live in seconds | 3600 |
views.* |
Enable caching per view type | varies |
gc_probability |
Probability of running garbage collection | 0.01 |
gc_divisor |
Divisor for probability calculation | 100 |
Usage Examples
Creating a Controller
Request Validation with DTOs
Define request DTOs in YAML:
Available property types:
string,integer,float,booleanemail,url,uuiddate,date_time,timecurrency,us_phone_number,intl_phone_numberarray,objectip_address,ein,upc,name,numeric
Error Handling
The framework automatically handles 404 errors:
Advanced Features
View Caching
The framework includes a sophisticated view caching system with multiple storage backends:
Storage Backends
- File Storage (Default): Uses the local filesystem for cache storage
- Redis Storage: High-performance in-memory caching with Redis
Features
- Automatic Cache Key Generation: Based on controller, view, and data
- Selective Caching: Enable/disable per view type
- TTL Support: Configure expiration times
- Garbage Collection: Automatic cleanup of expired entries
- Multiple Storage Backends: Choose between file or Redis storage
Configuration
File Storage Configuration
Redis Storage Configuration
This flat structure ensures compatibility with environment variables:
CACHE_STORAGE=redisCACHE_REDIS_HOST=127.0.0.1CACHE_REDIS_PORT=6379- etc.
Programmatic Usage
Manual Cache Management
Using CacheStorageFactory
You can also manage cache using the CLI commands. See CLI Commands section for details.
Custom View Implementations
Create custom view types by implementing IView:
Event System
Listen for HTTP events:
CLI Commands
The MVC component includes several CLI commands for managing cache and routes. These commands are available when using the Neuron CLI tool.
Cache Management Commands
mvc:cache:clear
Clear view cache entries.
Options:
--type, -t VALUE- Clear specific cache type (html, json, xml, markdown)--expired, -e- Only clear expired entries--force, -f- Clear without confirmation--config, -c PATH- Path to configuration directory
Examples:
mvc:cache:stats
Display comprehensive cache statistics.
Options:
--config, -c PATH- Path to configuration directory--json, -j- Output statistics in JSON format--detailed, -d- Show detailed breakdown by view type
Examples:
Sample Output:
Rate Limiting
The MVC component includes integrated rate limiting support through the routing component. Rate limiting helps protect your application from abuse and ensures fair resource usage.
Configuration
Rate limiting is configured in your neuron.yaml file using two categories:
Standard Rate Limiting
API Rate Limiting (Higher Limits)
Environment Variables
Configuration maps to environment variables using the {category}_{name} pattern:
RATE_LIMIT_ENABLED=trueRATE_LIMIT_STORAGE=redisRATE_LIMIT_REQUESTS=100API_LIMIT_ENABLED=trueAPI_LIMIT_REQUESTS=1000
Usage in Routes
Global Application
Set global: true in configuration to apply rate limiting to all routes:
Per-Route Application
Apply rate limiting to specific routes using the filters parameter in route attributes:
Storage Backends
File Storage (Default)
Best for single-server deployments:
Redis Storage (Recommended for Production)
Best for distributed systems and high traffic:
Memory Storage (Testing Only)
For unit tests and development. Data is lost when PHP process ends:
Rate Limit Headers
When rate limiting is active, the following headers are included in responses:
X-RateLimit-Limit: Maximum requests allowedX-RateLimit-Remaining: Requests remaining in current windowX-RateLimit-Reset: Unix timestamp when limit resets
When limit is exceeded (HTTP 429):
Retry-After: Seconds until retry is allowed
Example Implementation
-
Enable rate limiting in
neuron.yaml: - Apply to routes using attributes:
Customization
For advanced use cases, you can extend the rate limiting system by creating custom filters in your application. The rate limiting system automatically detects if the routing component version supports it and gracefully degrades if not available.
Route Management Commands
mvc:routes:list
List all registered routes with filtering options.
Options:
--config, -c PATH- Path to configuration directory--controller VALUE- Filter by controller name--method, -m VALUE- Filter by HTTP method (GET, POST, PUT, DELETE, etc.)--pattern, -p VALUE- Search routes by pattern--json, -j- Output routes in JSON format
Examples:
Sample Output:
API Reference
Bootstrap Functions
Boot(string $ConfigPath): Application
Initialize the application with configuration.
Dispatch(Application $App): void
Process the current HTTP request.
ClearExpiredCache(Application $App): int
Remove expired cache entries.
Key Interfaces
IController
All controllers must implement this interface:
renderHtml()- Render HTML with layoutrenderJson()- Render JSON responserenderXml()- Render XML response
IView
Views must implement:
render(array $Data): string- Render the view
ICacheStorage
Cache storage implementations must provide:
read(),write(),exists(),delete()clear()- Clear all entriesisExpired()- Check expirationgc()- Garbage collection
Testing
Run the test suite:
More Information
You can read more about the Neuron components at neuronphp.com
All versions of mvc with dependencies
ext-curl Version *
ext-json Version *
neuron-php/application Version 0.8.*
neuron-php/routing Version 0.8.*
neuron-php/dto Version 0.0.*
league/commonmark Version ^2.6
neuron-php/cli Version 0.8.*
neuron-php/orm Version 0.1.*
robmorgan/phinx Version ^0.16
neuron-php/jobs Version 0.2.*