Core runtime package for the MonkeysLegion PHP Framework, providing essential components including routing, middleware, dependency injection integration, logging, and helper utilities.
MonkeysLegion-Core is a foundational library that provides:
- Route Loading: Automatic controller discovery and route registration
- CORS Middleware: Advanced PSR-15 CORS handling with flexible origin matching
- Smart Logging: Environment-aware logging with PSR-3 compliance
- Helper Functions: Common utilities for path resolution and debugging
- Service Provider Interface: Standardized component registration
- PHP 8.4 or higher
- PSR-7 (HTTP Message)
- PSR-11 (Container)
- PSR-15 (HTTP Server Middleware)
- PSR-17 (HTTP Factories)
composer require monkeyscloud/monkeyslegion-coreThe RouteLoader automatically scans your controller directory and registers routes defined via attributes.
use MonkeysLegion\Core\Routing\RouteLoader;
$loader = new RouteLoader(
router: $router,
container: $container,
controllerDir: base_path('app/Controller'),
controllerNS: 'App\\Controller'
);
$loader->loadControllers();Features:
- Recursive directory scanning
- Automatic class instantiation via DI container
- Skips abstract classes
- Integrates with
monkeyscloud/monkeyslegion-router
The CorsMiddleware is a fully-featured PSR-15 middleware for handling Cross-Origin Resource Sharing.
use MonkeysLegion\Core\Middleware\CorsMiddleware;
$cors = new CorsMiddleware(
allowOrigin: ['https://example.com', '/^https:\/\/.*\.example\.com$/'],
allowMethods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
exposeHeaders: ['X-Total-Count'],
allowCredentials: true,
maxAge: 86400,
responseFactory: $responseFactory
);Features:
- Origin Matching: Supports wildcards (
*), exact strings, or PCRE patterns - Pre-flight Handling: Automatic OPTIONS request handling
- Credentials Support: Configurable
Access-Control-Allow-Credentials - Cache Safety: Adds
Vary: Originheader - Error Handling: Catches exceptions and returns JSON error responses
Defined in src/Support/helpers.php:
Returns an absolute path relative to the project root.
base_path(); // → /full/path/to/project
base_path('var/migrations'); // → /full/path/to/project/var/migrations
base_path('config/app.php'); // → /full/path/to/project/config/app.phpConfiguration:
- Define
ML_BASE_PATHconstant to set the project root - Falls back to
dirname(__DIR__, 4)for testing environments
Dump variables and terminate script execution.
dd($user, $order); // Dumps both variables and exitsFeatures:
- CLI-aware output (plain text vs HTML)
- XSS-safe HTML output for web contexts
- Handles arrays, objects, scalars, and null values
- Exits with status code 1
Get the value of an environment variable with automatic type conversion.
env('APP_ENV', 'production'); // Returns string
env('DEBUG', true); // Returns bool
env('DB_PORT', 3306); // Returns intFeatures:
- Checks
$_ENV,$_SERVER, andgetenv() - Converts string
'true','false','null', and'empty'to their PHP types
Returns an absolute path relative to the storage directory.
storage_path(); // → /full/path/to/project/storage
storage_path('logs'); // → /full/path/to/project/storage/logsThe absolute path to the config directory. By default, it uses base_path('config').
Loads a configuration file with environment-specific overrides. Throws a RuntimeException if the configuration is not found.
$config = require_config('app');Similar to require_config, but returns an empty array if the configuration file is not found.
$config = include_config('database');Configuration Merging:
- Both functions load
config/{name}.phpfirst. - Then merge environment-specific overrides from
config/{name}.{env}.php(where{env}is defined byAPP_ENV). - Uses
array_replace_recursive()for deep merging of nested settings.
The ProviderInterface standardizes how components register themselves with the framework.
interface ProviderInterface
{
public static function register(string $root, ContainerBuilder $c): void;
public static function setLogger(FrameworkLoggerInterface $logger): void;
}Implement this interface in your service providers for consistent component registration.
This package strictly adheres to PHP-FIG standards:
- PSR-7: HTTP Message Interface (used in
CorsMiddleware) - PSR-11: Container Interface (used in
RouteLoader) - PSR-15: HTTP Server Request Handlers (
CorsMiddleware) - PSR-17: HTTP Factories (
CorsMiddleware)
- Strict type declarations (
declare(strict_types=1)) - Full PHP 8.4 type hints
- PHPStan level max compliance
vendor/bin/phpstan analyseConfiguration: phpstan.neon
- Strict Types: All files use
declare(strict_types=1) - Final Classes: Components use
finalto prevent inheritance where appropriate - Type Hints: Full parameter and return type declarations
- PHPDoc: Comprehensive documentation blocks
use MonkeysLegion\Core\Routing\RouteLoader;
use MonkeysLegion\Core\Middleware\CorsMiddleware;
use MonkeysLegion\Core\Logger\MonkeyLogger;
// Set up logger
$logger = new MonkeyLogger($psrLogger, $_ENV['APP_ENV']);
// Configure CORS
$cors = new CorsMiddleware(
allowOrigin: ['https://app.example.com'],
allowMethods: ['GET', 'POST', 'PATCH', 'DELETE'],
allowCredentials: true
);
// Load routes
$routeLoader = new RouteLoader(
$router,
$container,
base_path('app/Controller'),
'App\\Controller'
);
$routeLoader->loadControllers();
// Add middleware to pipeline
$middleware->add($cors);php: ^8.4psr/container: ^2.0psr/log: ^3.0psr/http-message: ^2.0psr/http-server-handler: ^1.0psr/http-server-middleware: ^1.0psr/http-factory: ^1.1monkeyscloud/monkeyslegion-http: ^1.0monkeyscloud/monkeyslegion-router: ^1.0monkeyscloud/monkeyslegion-di: ^1.0
phpstan/phpstan: ^2.1
MIT License. See LICENSE file for details.
Contributions are welcome! Please ensure:
- Code follows PSR-12 coding standards
- All code passes PHPStan level max
- New features include appropriate documentation
- Type hints are comprehensive
For issues, questions, or contributions, please visit the project repository.