Complete API reference for core SPIN Framework classes, methods, and global helper functions.
The main application orchestrator managing the request/response lifecycle, routing, middleware execution, and dependency injection.
Namespace: Spin\Application
Key Methods:
| Method | Signature | Description |
|---|---|---|
__construct() |
public function __construct() |
Initialize the application instance |
run() |
public function run(): void |
Execute the application lifecycle and handle HTTP request |
getEnvironment() |
public function getEnvironment(): string |
Get current environment name |
getBasePath() |
public function getBasePath(): string |
Get application base path |
getAppPath() |
public function getAppPath(): string |
Get app folder path |
getConfig() |
public function getConfig(): ?Config |
Get Configuration object |
getLogger() |
public function getLogger(): ?Logger |
Get Logger instance |
getCache() |
public function getCache(): ?AbstractCacheAdapterInterface |
Get Cache adapter |
getConnectionManager() |
public function getConnectionManager(): ?ConnectionManager |
Get database connection manager |
getContainer() |
public function getContainer(): ?ContainerInterface |
Get PSR-11 service container |
getProperty() |
public function getProperty(string $property): mixed |
Get application property by name |
Usage Example:
$app = app(); // Get global application instance
$env = $app->getEnvironment(); // e.g., "development"
$config = $app->getConfig(); // Access configurationBase controller class providing HTTP method handlers and convenient access to framework services.
Namespace: Spin\Core\Controller
Key Methods:
| Method | Signature | Description |
|---|---|---|
initialize() |
public function initialize(array $args): void |
Called after controller instantiation, before middleware |
handle() |
public function handle(array $args): ResponseInterface |
Main dispatcher; routes to HTTP method handlers |
handleGET() |
public function handleGET(array $args): ResponseInterface |
Handle GET requests |
handlePOST() |
public function handlePOST(array $args): ResponseInterface |
Handle POST requests |
handlePUT() |
public function handlePUT(array $args): ResponseInterface |
Handle PUT requests |
handlePATCH() |
public function handlePATCH(array $args): ResponseInterface |
Handle PATCH requests |
handleDELETE() |
public function handleDELETE(array $args): ResponseInterface |
Handle DELETE requests |
handleHEAD() |
public function handleHEAD(array $args): ResponseInterface |
Handle HEAD requests |
handleOPTIONS() |
public function handleOPTIONS(array $args): ResponseInterface |
Handle OPTIONS requests |
Usage Example:
declare(strict_types=1);
namespace App\Controllers;
use Spin\Core\Controller;
use Psr\Http\Message\ResponseInterface;
class UserController extends Controller
{
public function initialize(array $args): void
{
// Setup controller state
}
public function handleGET(array $args): ResponseInterface
{
$userId = $args['id'] ?? null;
return responseJson(['user_id' => $userId]);
}
public function handlePOST(array $args): ResponseInterface
{
$data = json_decode(getRequest()->getBody(), true);
// Process creation
return responseJson(['status' => 'created'], 201);
}
}Base middleware class for request/response pipeline processing.
Namespace: Spin\Core\Middleware
Key Methods:
| Method | Signature | Description |
|---|---|---|
initialize() |
public function initialize(array $args): bool |
Setup phase; return false to fail |
handle() |
public function handle(array $args): bool |
Per-request processing; false short-circuits pipeline |
Execution Order: Global-before → Group-before → Controller → Group-after → Global-after
Usage Example:
declare(strict_types=1);
namespace App\Middleware;
use Spin\Core\Middleware;
class AuthMiddleware extends Middleware
{
public function initialize(array $args): bool
{
// Load auth config, setup
return true;
}
public function handle(array $args): bool
{
$token = getRequest()->getHeaderLine('Authorization');
if (!$this->validateToken($token)) {
responseJson(['error' => 'Unauthorized'], 401);
return false; // Short-circuit the pipeline
}
return true; // Continue
}
}Application configuration management with JSON-based files and dot-notation accessors.
Namespace: Spin\Core\Config
Key Methods:
| Method | Signature | Description |
|---|---|---|
__construct() |
public function __construct(string $appPath, string $environment) |
Load config-{environment}.json |
get() |
public function get(string $key, mixed $default = null): mixed |
Get config value by dot-notation key |
set() |
public function set(string $key, mixed $value): self |
Set config value by key |
has() |
public function has(string $key): bool |
Check if key exists |
load() |
public function load(string $filename): self |
Load and merge JSON config file |
all() |
public function all(): array |
Get all configuration as array |
clear() |
public function clear(): self |
Clear all values |
Dot Notation Examples:
$timeout = config('session.timeout'); // Get session timeout
$secret = config('application.secret'); // Get app secret
config('cache.driver', 'redis'); // Set cache driverPSR-3 compliant logger extending Monolog.
Namespace: Spin\Core\Logger
Key Methods (PSR-3):
| Method | Signature | Description |
|---|---|---|
emergency() |
public function emergency(string \$message, array \$context = []): void |
Emergency level |
alert() |
public function alert(string \$message, array \$context = []): void |
Alert level |
critical() |
public function critical(string \$message, array \$context = []): void |
Critical level |
error() |
public function error(string \$message, array \$context = []): void |
Error level |
warning() |
public function warning(string \$message, array \$context = []): void |
Warning level |
notice() |
public function notice(string \$message, array \$context = []): void |
Notice level |
info() |
public function info(string \$message, array \$context = []): void |
Informational level |
debug() |
public function debug(string \$message, array \$context = []): void |
Debug level |
log() |
public function log(\$level, string \$message, array \$context = []): void |
Log at level |
Usage Example:
$log = logger(); // Get global logger
$log->info('User login', ['user_id' => 123]);
$log->error('Database error', ['error' => 'Connection failed']);
logger()->debug('Debug info', ['payload' => $data]);PSR-16 compatible cache adapter manager supporting multiple backends.
Namespace: Spin\Core\CacheManager
Key Methods:
| Method | Signature | Description |
|---|---|---|
__construct() |
public function __construct(array \$options) |
Initialize with config options |
get() |
public function get(string \$key, mixed \$default = null): mixed |
Get cached value |
set() |
public function set(string \$key, mixed \$value, \$ttl = null): bool |
Set cache with optional TTL |
delete() |
public function delete(string \$key): bool |
Delete cache entry |
clear() |
public function clear(): bool |
Clear all cache |
getMultiple() |
public function getMultiple(iterable \$keys, mixed \$default = null): iterable |
Get multiple values |
setMultiple() |
public function setMultiple(iterable \$values, \$ttl = null): bool |
Set multiple values |
deleteMultiple() |
public function deleteMultiple(iterable \$keys): bool |
Delete multiple values |
has() |
public function has(string \$key): bool |
Check if key exists |
Supported Adapters:
- APCu - In-memory cache (requires PHP APCu extension)
- Redis - Distributed cache (via Predis)
- File - File-based cache (local storage)
Usage Example:
$cache = cache(); // Get global cache instance
$value = $cache->get('user_123'); // Get value
$cache->set('user_123', ['name' => 'John'], 3600); // 1-hour TTL
$cache->has('user_123'); // Check existence
$cache->delete('user_123'); // Delete entry
$cache->clear(); // Clear allDatabase connection pool manager supporting multiple drivers and databases.
Namespace: Spin\Core\ConnectionManager
Key Methods:
| Method | Signature | Description |
|---|---|---|
__construct() |
public function __construct(array \$connections) |
Initialize with connection configs |
connect() |
public function connect(string \$name = 'default'): ?PdoConnection |
Get/create connection |
disconnect() |
public function disconnect(string \$name = null): bool |
Close connection |
disconnectAll() |
public function disconnectAll(): bool |
Close all connections |
getConnection() |
public function getConnection(string \$name = 'default'): ?PdoConnection |
Get active connection |
Supported Drivers:
- MySQL
- PostgreSQL
- SQLite
- CockroachDB
- Firebird
- ODBC
Usage Example:
$db = db(); // Get default database connection
$db = db('secondary'); // Get named connection
$stmt = $db->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([123]);
$user = $stmt->fetch();Global helper functions available throughout the application for convenient access to framework services.
Get environment variable with type coercion support.
Signature: function env(string $var, mixed $default = null): mixed
$debug = env('DEBUG', false); // Coerces "true"/"false" to boolean
$port = env('PORT', 8000);
$custom = env('CUSTOM_VAR', 'default');Get the global Application instance or a specific property.
Signature: function app(?string $property = null): mixed
$app = app(); // Get Application instance
$env = app('environment'); // Get specific propertyGet/set configuration values using dot-notation keys.
Signature: function config(?string $key = null, mixed $value = null): mixed
$value = config('application.secret');
config('cache.driver', 'redis');
$allConfig = config(); // Get Config objectGet or set values in the PSR-11 dependency injection container.
Signature: function container(?string $id = null, mixed $value = null): mixed
$value = container('MyService');
container('MyKey', 'value');
container()->add('MyClass', 'App\\Custom\\MyClass');Get the global Logger instance (PSR-3 compliant).
Signature: function logger(): Logger
logger()->info('Application started');
logger()->error('Error occurred', ['exception' => $e]);Get a database connection from the ConnectionManager.
Signature: function db(?string $name = 'default'): ?PdoConnection
$db = db(); // Default connection
$db = db('secondary'); // Named connectionGet the global Cache adapter instance.
Signature: function cache(): ?AbstractCacheAdapterInterface
$value = cache()->get('key');
cache()->set('key', $value, 3600);Get the current PSR-7 ServerRequest instance.
Signature: function getRequest(): ?RequestInterface
$method = getRequest()->getMethod(); // GET, POST, etc.
$body = getRequest()->getBody();
$header = getRequest()->getHeaderLine('Authorization');Get the current PSR-7 Response instance.
Signature: function getResponse(): ?ResponseInterface
$response = getResponse();
$response = $response->withStatus(200);Create a text/HTML response.
Signature: function response(string $body, int $status = 200, array $headers = []): ResponseInterface
return response('<h1>Hello</h1>', 200, ['Content-Type' => 'text/html']);Create a JSON response.
Signature: function responseJson(mixed $data, int $status = 200, array $headers = []): ResponseInterface
return responseJson(['status' => 'success', 'data' => $user], 200);
return responseJson(['error' => 'Not found'], 404);Create an XML response.
Signature: function responseXml(array $data, int $status = 200, array $headers = []): ResponseInterface
return responseXml(['user' => ['id' => 1, 'name' => 'John']], 200);Create an HTML response with template rendering.
Signature: function responseHtml(string $html, int $status = 200, array $headers = []): ResponseInterface
return responseHtml('<div>Content</div>', 200);Create a file download response.
Signature: function responseFile(string $filepath, ?string $filename = null, int $status = 200): ResponseInterface
return responseFile('/path/to/file.pdf', 'download.pdf');Create a redirect response.
Signature: function redirect(string $location, int $status = 302): ResponseInterface
return redirect('/login');
return redirect('https://example.com', 301);Get a single query parameter from the request.
Signature: function queryParam(string $key, mixed $default = null): mixed
$page = queryParam('page', 1);
$search = queryParam('q');Get all query parameters as an array.
Signature: function queryParams(): array
$params = queryParams(); // ['page' => '1', 'sort' => 'name']Get a single POST parameter from the request body.
Signature: function postParam(string $key, mixed $default = null): mixed
$username = postParam('username');
$age = postParam('age', 0);Get all POST parameters as an array.
Signature: function postParams(): array
$params = postParams(); // ['username' => 'john', 'password' => '...']Get a single cookie value.
Signature: function cookieParam(string $key, mixed $default = null): mixed
$sessionId = cookieParam('SESSIONID');Get all cookies as an array.
Signature: function cookieParams(): array
$cookies = cookieParams(); // ['SESSIONID' => '...', ...]Set a response cookie.
Signature: function cookie(string $name, string $value, array $options = []): bool
cookie('session_id', '12345', ['expires' => time() + 3600]);
cookie('remember', 'user123', ['path' => '/', 'secure' => true]);Get the client's IP address from the request.
Signature: function getClientIp(): ?string
$ip = getClientIp(); // e.g., "192.168.1.1"Generate a unique reference ID for tracking.
Signature: function generateRefId(): string
$refId = generateRefId(); // e.g., "REF-20250315-abc123"Framework exception classes for error handling.
Base exception class for all SPIN Framework exceptions.
Namespace: Spin\Exceptions\SpinException
try {
// Framework operation
} catch (SpinException $e) {
logger()->error('SPIN error', ['message' => $e->getMessage()]);
}Thrown when configuration errors occur.
Namespace: Spin\Exceptions\ConfigException
try {
$value = config('missing.key');
} catch (ConfigException $e) {
// Handle config error
}Thrown for database operation errors.
Namespace: Spin\Exceptions\DatabaseException
try {
$db->prepare('SELECT * FROM users')->execute();
} catch (DatabaseException $e) {
logger()->error('Database error', ['message' => $e->getMessage()]);
}Thrown for cache adapter errors.
Namespace: Spin\Exceptions\CacheException
try {
cache()->set('key', $value);
} catch (CacheException $e) {
// Handle cache error
}Thrown when middleware processing fails.
Namespace: Spin\Exceptions\MiddlewareException
try {
// Middleware initialization
} catch (MiddlewareException $e) {
// Handle middleware error
}Manages cache adapter instances and operations.
Configuration Example:
{
"cache": {
"default": "apcu",
"adapters": {
"apcu": {
"driver": "apcu"
},
"redis": {
"driver": "redis",
"host": "localhost",
"port": 6379,
"ttl": 3600
},
"file": {
"driver": "file",
"path": "storage/cache"
}
}
}
}Manages database connections with pooling and lazy loading.
Configuration Example:
{
"database": {
"default": "mysql",
"connections": {
"mysql": {
"driver": "mysql",
"host": "localhost",
"port": 3306,
"database": "myapp",
"username": "${env:DB_USER}",
"password": "${env:DB_PASSWORD}"
},
"postgresql": {
"driver": "postgresql",
"host": "localhost",
"port": 5432,
"database": "myapp",
"username": "${env:DB_USER}",
"password": "${env:DB_PASSWORD}"
}
}
}
}- Configuration — JSON-based configuration
- Routing — Route definition and handling
- Middleware — Middleware pipeline
- Databases — Database operations
- Cache — Caching strategies
- Helpers — Additional utility functions