Registering Helper Functions via Composer Autoload
In Hyperf applications, you can create global helper functions to access core components more conveniently. These functoins provide shortcuts to services like Redis, caching, logging, and WebSocket connections.
Creating the Helper File
Create a helper file that defines global functions for accessing Hyperf's core services. Place this file in your application directory and register it through Composer's autoload mechanism.
<?php
use Hyperf\Contract\SessionInterface;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Server\ServerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerInterface;
use Psr\SimpleCache\CacheInterface;
use Swoole\Websocket\Frame;
use Swoole\WebSocket\Server as WsServer;
if (!function_exists('app')) {
/**
* Obtain the PSR-11 container instance
*/
function app(): ContainerInterface
{
return ApplicationContext::getContainer();
}
}
if (!function_exists('rd')) {
/**
* Obtain the Redis client instance
*/
function rd(): Hyperf\Redis\Redis
{
return app()->get(Hyperf\Redis\Redis::class);
}
}
if (!function_exists('srv')) {
/**
* Obtain the underlying Swoole server instance
*/
function srv(): \Swoole\Server
{
return app()->get(ServerFactory::class)->getServer()->getServer();
}
}
if (!function_exists('ws_frame')) {
/**
* Obtain the WebSocket frame instance
*/
function ws_frame(): Frame
{
return app()->get(Frame::class);
}
}
if (!function_exists('ws_server')) {
/**
* Obtain the WebSocket server instance
*/
function ws_server(): WsServer
{
return app()->get(WsServer::class);
}
}
if (!function_exists('store')) {
/**
* Obtain the simple cache instance
*/
function store(): CacheInterface
{
return app()->get(CacheInterface::class);
}
}
if (!function_exists('console')) {
/**
* Obtain the console logger for stdout output
*/
function console(): StdoutLoggerInterface
{
return app()->get(StdoutLoggerInterface::class);
}
}
if (!function_exists('log')) {
/**
* Obtain a file logger instance
*/
function log(): \Psr\Log\LoggerInterface
{
return app()->get(LoggerFactory::class)->make();
}
}
if (!function_exists('req')) {
/**
* Obtain the current request instance
*/
function req(): RequestInterface
{
return app()->get(RequestInterface::class);
}
}
if (!function_exists('res')) {
/**
* Obtain the response instance
*/
function res(): ResponseInterface
{
return app()->get(ResponseInterface::class);
}
}
if (!function_exists('sess')) {
/**
* Obtain the session instance
*/
function sess(): SessionInterface
{
return app()->get(SessionInterface::class);
}
}
Configuring Composer Autoload
Register the helper file in your project's composer.json under the autoload section:
{
"autoload": {
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Helpers/functions.php"
]
}
}
After adding the file to composer.json, run composer dump-autoload to regenerate the autoloader.
Usage Examples
The following examples demonstrate how to use each helper function in a controller or service class:
/**
* Demonstrate helper function usage - Part 1
*/
public function demonstrate(): \Psr\Http\Message\ResponseInterface
{
// File-based logging
log()->error('Application error occurred');
// Console output logging
console()->info('Operation completed successfully');
// Retrieve input parameters from the request
$inputValue = req()->input('parameter_key');
// Store data in Redis cache
store()->set('cache_key', 'cached_data_value');
// Retrieve Swoole server information
$masterPid = srv()->getMasterPid();
$managerPid = srv()->getManagerPid();
$currentWorkerId = srv()->getWorkerId();
$currentWorkerPid = srv()->getWorkerPid();
$workerStats = srv()->getWorkerStatus($currentWorkerId);
$statusInfo = "master={$masterPid}, manager={$managerPid}, worker_id={$currentWorkerId}, pid={$currentWorkerPid}, stats={$workerStats}";
// Store session data
sess()->put('user_session_data', 'session_value_here');
// Access WebSocket frame (requires active WebSocket connection)
// $connectionFd = ws_frame()->fd;
// Return response
return res()->raw('Status: ' . $statusInfo);
}
/**
* Demonstrate helper function usage - Part 2
*/
public function retrieveData(): \Psr\Http\Message\ResponseInterface
{
// Retrieve cached value
$cachedValue = store()->get('cache_key');
// Retrieve session value
$sessionValue = sess()->get('user_session_data');
$sessionIdentifier = sess()->getId();
$result = "Cached: {$cachedValue}, Session: {$sessionValue}, ID: {$sessionIdentifier}";
return res()->raw('Data: ' . $result);
}
Helper Function Reference
| Function | Returns | Description |
|---|---|---|
app() |
ContainerInterface | PSR-11 container instance |
rd() |
Redis | Redis client for caching and data storage |
srv() |
Swoole\Server | Core Swoole server for process management |
store() |
CacheInterface | Simple cache interface for temporary storage |
log() |
LoggerInterface | File-based logging service |
console() |
StdoutLoggerInterface | Console output logging |
req() |
RequestInterface | Current HTTP request handling |
res() |
ResponseInterface | HTTP response construction |
sess() |
SessionInterface | Session state management |
ws_frame() |
Frame | WebSocket frame data |
ws_server() |
WsServer | WebSocket server instacne |