PHP code example of narya / php-sdk

1. Go to this page and download the library: Download narya/php-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

narya / php-sdk example snippets




declare(strict_types=1);

se Narya\SDK\Runtime\WorkerResponse;
use Narya\SDK\Contracts\ApplicationWorker;
use Narya\SDK\Contracts\NaryaRequest;

$app = new class () implements ApplicationWorker {
    public function handle(NaryaRequest $request): array|WorkerResponse
    {
        if ($request->getPath() === '/health' && $request->getMethod() === 'GET') {
            return WorkerResponse::create(200, ['Content-Type' => ['application/json']], '{"status":"ok"}', '');
        }
        return WorkerResponse::create(404, [], '', 'Not Found');
    }

    public function reset(): void
    {
        // Clear per-request state (superglobals, connections, etc.)
    }
};

(new Worker($app))->run();

use Narya\SDK\Lifecycle\LifecycleManager;

$lifecycle = new LifecycleManager();

// Run once when the worker starts (before connecting to the socket)
$lifecycle->onBoot(function (): void {
    // e.g. open persistent DB connection, warm cache, load config
    // MyApp::connectDb();
    // MyApp::warmCache();
});

// Run when the loop ends (max_requests reached, EOF from Go, or exception)
$lifecycle->onShutdown(function (): void {
    // e.g. close connections, flush logs, cleanup
    // MyApp::closeDb();
    // MyApp::flushLogs();
});

(new Worker($app, null, 10000, $lifecycle))->run();

// Simple container: boot() sets it, shutdown() clears it, app uses it in handle()
class WorkerContainer {
    public static ?PDO $db = null;
}

$lifecycle = new LifecycleManager();
$lifecycle->onBoot(function (): void {
    WorkerContainer::$db = new PDO('sqlite::memory:'); // or real DSN
});
$lifecycle->onShutdown(function (): void {
    WorkerContainer::$db = null;
});

$app = new class () implements ApplicationWorker {
    public function handle(NaryaRequest $request): array|WorkerResponse {
        $db = WorkerContainer::$db; // available for the whole loop (until shutdown)
        // use $db for queries...
        return WorkerResponse::create(200, ['Content-Type' => ['application/json']], '{"ok":true}', '');
    }
    public function reset(): void {}
};

(new Worker($app, null, 10000, $lifecycle))->run();

$handler = function (array $request): array {
    return [
        'status' => 200,
        'headers' => ['Content-Type' => ['application/json']],
        'body' => '{"message":"Hello"}',
        'error' => '',
    ];
};

(new Worker(null, $handler))->run();
bash
composer