API Reference

Core API and helper functions reference

Quick reference for Glueful's core APIs and helper functions.

Global Helpers

app()

Get service from container

$db = app('database'); // or app(DatabaseInterface::class)
$cache = app('cache'); // or app(CacheInterface::class)

database (via container)

Get database connection (no db() helper; use the container)

$db = app('database'); // Glueful\Database\Connection

// Query builder entrypoints
$users = $db->table('users')->where('status', 'active')->get();
$users = $db->query()->from('users')->where('status', 'active')->get();

cache (via container)

Get cache instance (no cache() helper; use the container)

$cache = app('cache.store'); // or app(Glueful\Cache\CacheStore::class)
$cache->set('key', 'value', 3600);
$value = $cache->get('key');

config()

Get configuration value

$appName = config('app.name');
$dbHost = config('database.host');

env()

Get environment variable

$apiKey = env('API_KEY');
$debug = env('APP_DEBUG', false);

logger (via container)

Get logger instance (no logger() helper; use the container)

$logger = app('logger'); // or app(Psr\Log\LoggerInterface::class)
$logger->info('Message', ['context' => 'value']);
$logger->error('Error occurred', ['error' => $e->getMessage()]);

Database

Query Builder

// Entrypoints
$db = app('database');
$db->table('users')->get();
$db->table('users')->where('status', 'active')->get();

// Insert/Update/Delete (return ints)
$db->table('users')->insert(['name' => 'John', 'email' => '[email protected]']);
$db->table('users')->where('id', $id)->update(['name' => 'Jane']);
$db->table('users')->where('id', $id)->delete();

// Using query()->from(...)
$db->query()->from('users')->select(['id','name'])->get();

// Joins
$db->query()
    ->from('users')
    ->join('orders', 'users.id', '=', 'orders.user_id')
    ->select(['users.*', 'orders.total'])
    ->get();

// Aggregates
$db->query()->from('orders')->count();
$db->query()->from('orders')->max('total');

// Pagination
$db->query()->from('orders')->paginate(page: 1, perPage: 15);

// Optional: enable query result caching
$db->query()->from('users')->where('active', 1)->cache(3600)->get();

See Database Guide for full reference.

Cache

// Set
$cache = app('cache.store');
$cache->set('key', 'value', 3600);

// Get
$value = $cache->get('key');
$value = $cache->get('key', 'default');

// Remember pattern (pseudo if implemented)
$users = $cache->remember('users:active', function() use ($db) {
    return $db->table('users')->where('status', 'active')->get();
}, 3600);

// Check existence
if ($cache->has('key')) { /* ... */ }

// Delete
$cache->delete('key');
// $cache->deletePattern('users:*'); // If pattern deletion supported by driver (Redis/File)

// Clear all
$cache->clear();

See Caching Guide for full reference.

Queue

// Obtain queue manager
$queue = app('queue'); // or app(Glueful\Queue\QueueManager::class)

// Push job (use job class name + payload)
$queue->push(SendEmailJob::class, ['userId' => $userId]);

// Delayed job
$queue->later(60, ProcessImageJob::class, ['path' => $path]);

// Push to specific queue
$queue->push(SendEmailJob::class, ['userId' => $userId], queue: 'emails');

// Bulk
$queue->bulk([
    ['job' => Job1::class, 'data' => ['id' => 1]],
    ['job' => Job2::class, 'data' => ['id' => 2]],
]);

See Queues & Jobs Guide for full reference.

Events

// Dispatch (using event dispatcher service)
app(Glueful\Events\EventDispatcher::class)->dispatch(new UserRegistered($user));

// Listener registration typically happens via service providers / attributes.
// Inline listening (if supported) would use dispatcher subscribe API.

See Events Guide for full reference.

HTTP

Request

$request->getMethod();                // GET, POST, etc.
$request->getPathInfo();              // /api/users
$request->getUri();                   // Full URI
$request->get('name');                // Single input value
$request->request->all();             // POST body params
// Selecting specific fields:
$data = $request->request->all();
$subset = array_intersect_key($data, array_flip(['name','email']));
isset($data['name']);                 // Existence check
$request->files->get('avatar');       // Uploaded file
$request->headers->get('Authorization'); // Header
$request->getClientIp();              // Client IP
$request->headers->get('User-Agent'); // User agent
// Authenticated user (via auth helper/service)
$authUser = auth()?->user(); // or app(Glueful\Auth\AuthenticationService::class)->getCurrentUser()

Response

// Success
Response::success($data);
Response::created($data); // 201 Created

// Error
Response::error('Not found', 404);
Response::error('Validation failed', 422, ['errors' => $errors]);

// Headers
$resp = Response::success($data)->header('X-Custom', 'value');

See Requests & Responses Guide for full reference.

Validation

// Rule-object validation via ValidatorInterface
use Glueful\Helpers\RequestHelper;
use Glueful\Validation\Validator;
use Glueful\Validation\Rules\{Required, Type, Length, Email, Range};

$input = RequestHelper::getRequestData($request);

$rules = [
    'name' => [new Required(), new Type('string'), new Length(min: 3, max: 255)],
    'email' => [new Required(), new Email()],
    'password' => [new Required(), new Length(min: 8)],
    'age' => [new Required(), new Type('integer'), new Range(min: 18)],
];

$validator = new Validator($rules);
$errors = $validator->validate($input);
if ($errors !== []) {
    return Response::validation($errors);
}

Available Rules (objects)

  • Required - Field must be present
  • Type('string'|'integer'|...) - Type check
  • Length(min?, max?) - String length
  • Range(min?, max?) - Numeric range
  • Email() - Valid email
  • InArray([...]) - Must be in list
  • DbUnique(...) - Database uniqueness
  • Sanitize(...) - Value sanitization

See Validation Guide for full reference.

Authentication

$authService = app(Glueful\Auth\AuthenticationService::class);

// Login (username or email)
$session = $authService->authenticate(['username' => $email, 'password' => $password]);

// Get authenticated user (object) from context
$user = auth()?->user();

// Check authentication
if (auth()?->check()) {
    // Authenticated
}

// Logout / terminate session
$authService->terminateSession($token);

See Authentication Guide for full reference.

File Storage

// Storage via services
$storage = app(Glueful\Storage\StorageManager::class);
$disk = $storage->disk(); // default disk from config

// Write/read using Flysystem operator
$disk->write('avatars/user-1.png', $binaryContents);
$contents = $disk->read('avatars/user-1.png');
if ($disk->fileExists('avatars/user-1.png')) { /* ... */ }
$disk->delete('avatars/user-1.png');

// JSON helpers
$storage->putJson('data/users/1.json', ['id' => 1]);
$data = $storage->getJson('data/users/1.json');

// Public URL
$url = app(Glueful\Storage\Support\UrlGenerator::class)
    ->url('avatars/user-1.png');

See File Uploads Guide for full reference.

Logging

logger()->debug('Debug info', ['data' => $data]);
logger()->info('Info message', ['user_id' => $userId]);
logger()->warning('Warning', ['key' => $key]);
logger()->error('Error occurred', ['error' => $e->getMessage()]);
logger()->critical('Critical failure');

See Logging Guide for full reference.

Next Steps