gCore

gCore Framework Documentation

Overview

gCore is a distributed PHP framework designed to provide service management with zero local state and discovery on the constellation's one topology. It offers WordPress integration capabilities while maintaining compatibility with standalone PHP applications, Docker environments, and CLI tools.

The core of the framework is composed of four main managers (the Manager Quartet):

All managers follow a trait-based architecture where functionality can be dynamically composed at runtime based on configuration and actual usage patterns.

System Architecture

gCore sites register on the constellation's one topology and find other services by facet and axis range through the gNode daemon.

Key architectural principles:

Installation and Setup

Requirements

Basic Installation

  1. Clone the repository
  2. Install dependencies with Composer
  3. Configure the .env file with ValKey/Redis connection details
  4. Initialize the system with php gCoreCLI.php init

WordPress Integration

When used with WordPress:

  1. Install as a plugin by placing in the wp-content/plugins directory
  2. Activate the plugin through the WordPress admin interface
  3. Configure settings through the gCore admin panel in WordPress

Core Managers

1. gCore System

The gCore class is the central orchestrator of the entire system. It handles initialization, service management, and dependency resolution.

Key Functions

// Include the standalone initialization script
require_once 'gcore-standalone.php';

// Initialize the system
$gCore = gcore_init([
    'core' => [
        'environment' => 'production',
        'debug' => false
    ],
    'site_id' => 'my_site',
    'node_id' => 'node1'
]);

// Get manager instances using helper functions
$errorManager = gcore_get_error_manager();
$cacheManager = gcore_get_cache_manager();
$securityManager = gcore_get_security_manager();
$apiManager = gcore_get_api_manager();

// Or get a service directly through gCore
$anotherService = $gCore->getService('CustomService');

// Check system status
$status = $gCore->getStatus();

// Shutdown the system when done
gcore_shutdown();

Configuration Options

2. Security Manager

The SecurityManager handles authentication, data validation, encryption, and overall security of the application.

Key Functions

// Initialize
$securityManager = new \gCore\Modules\Managers\Base\SecurityManager\SecurityManager();
$securityManager->initialize([
    'site_id' => 'my_site',
    'node_id' => 'security_node',
    'environment' => 'production'
]);

// Encryption (requires CryptoTrait)
$encrypted = $securityManager->encrypt('sensitive data');
$decrypted = $securityManager->decrypt($encrypted);

// Data validation (requires SanitationTrait)
$cleaned = $securityManager->sanitize($_POST['user_input'], 'text');
$isValid = $securityManager->validate($data, 'email');

// Security monitoring (requires SecurityMonitoringTrait)
$securityManager->logSecurityEvent('login_attempt', [
    'username' => $username,
    'ip' => $_SERVER['REMOTE_ADDR'],
    'success' => $success
]);

// Get security status
$status = $securityManager->getStatus();

Available Traits

3. Error Manager

The ErrorManager provides error tracking, logging, and notification capabilities with full multi-tenant isolation.

Key Functions

// Initialize
$errorManager = new \gCore\Modules\Core\Managers\Base\ErrorManager();
$errorManager->initialize([
    'site_id' => 'my_site',
    'node_id' => 'error_node',
    'environment' => 'production',
    'admin_email' => 'admin@example.com'
]);

// Log errors with different severity levels
$errorManager->logError('Database connection failed', [
    'host' => $host,
    'error' => $e->getMessage()
], 'CRITICAL', 'DATABASE');

// Process error queue (for batch processing)
$errorManager->processErrorQueue();

// Get error metrics
$metrics = $errorManager->getMetrics();

// Check system health
$health = $errorManager->getClusterHealth();

Error Severity Levels

Error Categories

4. Cache Manager

The CacheManager provides high-performance distributed caching with ValKey/Redis backend, supporting advanced features like streams, transactions, and locks.

Key Functions

// Initialize
$cacheManager = new \gCore\Modules\Managers\Base\CacheManager\CacheManager();
$cacheManager->initialize([
    'host' => '127.0.0.1',
    'port' => 6379,
    'auth' => 'password',
    'prefix' => 'mycache_',
    'timeout' => 2.0,
    'streams' => [
        'enabled' => true
    ]
]);

// Basic cache operations
$cacheManager->set('user:123', $userData, 'users', 3600);
$userData = $cacheManager->get('user:123', null, 'users');
$cacheManager->delete('user:123', 'users');

// Multiple operations
$cacheManager->setMultiple([
    'key1' => 'value1',
    'key2' => 'value2'
], 'group1', 3600);

$values = $cacheManager->getMultiple(['key1', 'key2'], 'group1');

// Atomic operations
$cacheManager->increment('counter', 1);
$cacheManager->decrement('counter', 1);

// Locks
$cacheManager->acquireLock('resource_lock', 30);
// Do something with exclusive access
$cacheManager->releaseLock('resource_lock');

// Transactions
$txId = $cacheManager->beginTransaction();
// Perform multiple operations
$cacheManager->commitTransaction($txId);
// Or if error
$cacheManager->rollbackTransaction($txId);

// Stream operations (requires StreamCapabilities trait)
$cacheManager->streamAdd('events', ['type' => 'user_login', 'user_id' => 123]);
$cacheManager->streamCreateGroup('events', 'processors');
$cacheManager->streamConsume('events', 'processors', 'worker1', function($message) {
    // Process message
});

Advanced Features

5. API Manager

The APIManager provides REST API management with endpoint registration, request processing with middleware, response caching, rate limiting, and metrics collection.

Key Functions

// Initialize
$apiManager = gcore_get_api_manager();

// Or initialize directly
$apiManager = new \gCore\Modules\Managers\Base\APIManager\APIManager();
$apiManager->initialize([
    'site_id' => 'my_site',
    'node_id' => 'api_node',
    'namespace' => 'myapp/v1',
    'cache_enabled' => true,
    'rate_limiting' => true,
    'server' => [
        'mode' => 'auto',   // Options: 'auto', 'standalone', 'integrated', 'disabled'
        'port' => 8000,     // Port for standalone server
        'host' => '0.0.0.0' // Host for standalone server
    ]
]);

// Register an endpoint with path parameters
$apiManager->registerEndpoint('users/{id}', [
    'methods' => 'GET',
    'callback' => function($request) {
        $userId = $request['path_params']['id'];
        return [
            'user' => [
                'id' => $userId,
                'name' => 'Example User'
            ]
        ];
    }
]);

// Add middleware
$apiManager->addMiddleware('auth', function($request, $next) {
    if (!isset($request['headers']['X-API-Key'])) {
        return [
            'status' => 'error',
            'code' => 401,
            'message' => 'Unauthorized'
        ];
    }
    return $next($request);
});

// Apply middleware to endpoints
$apiManager->registerEndpoint('secure/data', [
    'methods' => 'GET',
    'middleware' => ['auth'],
    'callback' => function() {
        return ['data' => 'Secure data'];
    }
]);

// In WordPress context
add_action('rest_api_init', function() use ($apiManager) {
    $apiManager->registerEndpoint('example', [
        'methods' => 'GET',
        'callback' => function($request) {
            return ['message' => 'Example endpoint'];
        },
        'permission_callback' => function() {
            return current_user_can('read');
        }
    ]);
});

// Start the server (in standalone mode)
$apiManager->startServer();

// Get API status
$status = $apiManager->getAPIStatus();

// Clear API cache
$apiManager->clearCache();

// Get API metrics
$metrics = $apiManager->getMetrics();

Available Traits

Server Modes

The APIManager supports multiple server operation modes:

Configuration System

gCore uses a hierarchical configuration system with YAML files. Configuration can be provided through:

  1. Default configuration files
  2. Environment-specific configuration
  3. Runtime configuration

Configuration Files

Configuration Hierarchy (Priority Order)

  1. Runtime configuration (passed to initialize())
  2. Environment variables
  3. Environment-specific configuration
  4. Default configuration

Service Discovery

A constellation has one topology, {<c>}:gnode:constellation, held in ValKey and maintained by the gNode daemon. A site declares itself on it by name (a shape, an environment and axis words); the daemon encodes the declaration. Cross-service lookup is a query over a layer by facet and axis range.

$topology = gCore::getService('TopologyManager');

$topology->smartRegister(['protocol' => 'http'], ['name' => 'Shop']);

$apps = $topology->discoverServices(['protocol' => ['resp3']], 5, 'app');

Resolving a manager inside the process (getService) is a local lookup and does not touch the topology.

WordPress Integration

gCore can be used as a WordPress plugin, providing advanced capabilities within the WordPress ecosystem.

WordPress-specific Features

WordPress Hooks

// Register custom endpoint
add_action('rest_api_init', [$apiManager, 'registerRestRoutes']);

// Add admin pages
add_action('admin_menu', [$apiManager, 'registerAdminPages']);

// Enqueue admin assets
add_action('admin_enqueue_scripts', [$apiManager, 'enqueueAdminAssets']);

// Handle post updates for cache invalidation
add_action('save_post', [$apiManager, 'invalidateCacheOnSave']);

Multi-tenant / Multi-site Support

gCore provides multi-tenant isolation through site-specific key prefixing.

Multi-tenant Features

ValKey Integration

gCore uses ValKey (a Redis fork) as its distributed backend. The ValKey integration provides:

Security Best Practices

gCore implements security best practices throughout the system:

Troubleshooting and FAQ

Common Issues

  1. ValKey Connection Issues

    • Ensure ValKey server is running
    • Check connection credentials
    • Verify network connectivity
  2. Trait Loading Failures

    • Verify trait configuration
    • Check for circular dependencies
    • Ensure trait path is correct
  3. WordPress Integration Problems

    • Verify WordPress version compatibility
    • Check plugin activation status
    • Ensure all required PHP extensions are installed

FAQ

Q: Can gCore work without ValKey/Redis? A: No, ValKey or Redis is required for core functionality as it provides the distributed backend for zero local state.

Q: Is gCore compatible with shared hosting? A: Limited compatibility. gCore works best on environments where you control the PHP configuration and have Redis/ValKey available. Docker deployment is recommended for easier setup.

Q: Can I use gCore without WordPress? A: Yes, gCore can be used in standalone PHP applications, with Docker, or via the CLI tools.

Q: What's the minimum PHP version required? A: PHP 8.1 or newer.

Q: How does gCore handle high traffic? A: gCore uses connection pooling, batched operations, and caching strategies to handle high traffic efficiently. The framework includes circuit breaker patterns, exponential backoff with jitter, and adaptive timeout adjustment.

Q: Does gCore support API server functionality out of the box? A: Yes, the APIManager provides a complete API server with support for multiple operation modes, middleware processing, path parameters, and rate limiting.

Q: Is gCore production-ready? A: All core managers are operational and have been validated through testing, including the MessageBroker example which integrates all four managers. See the test suite for current coverage.

Q: How can I monitor gCore's performance? A: Each manager provides built-in metrics collection and monitoring capabilities. The CLI tools also include monitoring commands for system health.

API Reference

For a complete API reference, please see the individual manager documentation: