stilmark/base

Shared core functions for web apps

Maintainers

Details

github.com/Stilmark/Base

Source

Issues

Installs: 32

Dependents: 1

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 6

Type:package

pkg:composer/stilmark/base

1.7.4 2025-10-09 18:32 UTC

This package is auto-updated.

Last update: 2025-10-09 18:34:14 UTC


README

License: MIT PHP Version Composer CodeFactor

A lightweight PHP utility library providing essential functionality for modern web applications. Base serves as a foundation for building PHP applications with clean, reusable components.

Features

  • Environment Management: Load and access .env variables.
  • Request Handling: A unified interface for HTTP requests, including input retrieval, validation, and sanitization.
  • Routing: A simple and fast router with middleware support.
  • Controllers: A base controller to extend for application logic.
  • Response Rendering: Helpers for sending JSON and CSV responses.
  • Session Management: Secure session handling with timeout management and flash data support.
  • CSRF Protection: Time-bucketed CSRF tokens with automatic rotation and origin validation.
  • Authentication: Multi-provider OAuth2 support (e.g., Google) with session regeneration and timeout management.
  • JWT Support: JSON Web Token generation and validation with configurable claims and expiration.
  • Logging: PSR-3 compliant logging with built-in Rollbar integration.
  • Helper Utilities: Static methods for common tasks like string manipulation.

Requirements

  • PHP: version 8.2 or higher
  • Composer for dependency management

Dependencies

Base relies on the following libraries (installed via Composer):

Installation

Install via Composer:

composer require stilmark/base

Quick Start

1. Basic Setup

Create a bootstrap file (index.php):

<?php
require __DIR__ . '/vendor/autoload.php';

use Stilmark\Base\Env;
use Stilmark\Base\Router;

// Load environment variables
Env::load(__DIR__ . '/.env');

// Initialize and dispatch routes
$router = new Router();
$router->addRoute('GET', '/', 'BaseApp\\Controller\\HomeController@index');
$router->dispatch();

2. Environment Configuration

Copy .env.example to .env and configure:

cp vendor/stilmark/base/.env.example .env

3. Create Your First Controller

<?php
namespace BaseApp\Controller;

use Stilmark\Base\Controller;

class HomeController extends Controller
{
    public function index()
    {
        return $this->json([
            'message' => 'Welcome to Stilmark Base!',
            'timestamp' => date('c')
        ]);
    }
}

Core Components

Component Description
Env Loads and manages environment variables from .env.
Request Provides a unified interface for handling HTTP requests, including input retrieval, validation, sanitization, and CSRF token generation/validation.
Router Handles routing, controller/method resolution, and middleware execution.
Controller Base class for application controllers.
Render Provides helper methods for rendering JSON and CSV responses.
Session Secure session management with timeout tracking, flash data, and security configuration.
Auth Handles multi-provider OAuth2 login flows (e.g., Google) with automatic session regeneration.
AuthMiddleware Validates session-based or JWT authentication with idle and absolute timeout management.
CsrfMiddleware Automatic CSRF protection for unsafe HTTP methods with time-bucketed token validation.
JWT JSON Web Token generation and validation.
Logger PSR-3 compliant logger with built-in Rollbar integration.
Helper Provides static utility methods (e.g., string case conversion).

Usage Examples

Environment Variables

use Stilmark\Base\Env;

Env::load('.env');
$apiUrl = Env::get('API_URL', 'https://api.default.com');
Env::set('RUNTIME_FLAG', true);

Request Handling

use Stilmark\Base\Request;

$request = new Request();
$userId = $request->get('user_id');
$jsonData = $request->json();
$uploadedFile = $request->file('avatar');

Authentication

use Stilmark\Base\Auth;

$auth = new Auth();
$auth->callout(); // Redirect to Google OAuth

// In callback route:
$user = $auth->callback($request);
$_SESSION['user'] = $user;

Session Management

use Stilmark\Base\Session;

// Configure session security (before session_start)
Session::configure([
    'cookie_secure' => true,
    'cookie_samesite' => 'Strict',
]);

session_start();

// Set and get session data
Session::set('user_id', 123);
$userId = Session::get('user_id');

// Flash messages
Session::flash('success', 'Login successful!');
$message = Session::getFlash('success'); // Retrieved once

CSRF Protection

use Stilmark\Base\Request;
use Stilmark\Base\CsrfMiddleware;

session_start();

// Generate token for forms
$request = new Request();
$csrfToken = $request->generateCsrfToken();

// Validate with middleware
$csrfMiddleware = new CsrfMiddleware(['https://example.com']);
if (!$csrfMiddleware->handle()) {
    http_response_code(403);
    exit('CSRF validation failed');
}

JWT Usage Example

use Stilmark\Base\Jwt;

// Generate a JWT token
$token = Jwt::generate([
    'user_id' => 123,
    'email' => 'user@example.com'
]);

// Validate and decode the token
try {
    $decoded = Jwt::validate($token);
    echo "User ID: " . $decoded->user_id;
} catch (Exception $e) {
    echo "Invalid token: " . $e->getMessage();
}

Documentation

Complete Documentation

Related Projects

  • BaseApp - Full application framework built on Base

License

This project is licensed under the MIT License - see the LICENSE file for details.

Author

Christian Lund