PHP code example of laikait / laika-relay

1. Go to this page and download the library: Download laikait/laika-relay 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/ */

    

laikait / laika-relay example snippets


use Laika\Relay\RelayRegistry;

$registry = new RelayRegistry();

$registry->instance(string $key, object $instance): static

$pdo = new PDO($dsn, $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$registry->instance('db', $pdo);

$registry->singleton(string $key, Closure|string $concrete, array $args = []): static

// Class string — no args needed
$registry->singleton('session', Session::class);

// Class string — with primitive args (positional)
$registry->singleton('mailer', Mailer::class, ['smtp']);

// Class string — with primitive args (named)
$registry->singleton('queue', DatabaseDriver::class, [
    'table'   => 'async_jobs',
    'retries' => 3,
]);

// Closure — manual control, receives the registry
$registry->singleton('db', function (RelayRegistry $r) {
    $config = $r->make('config');
    $pdo    = new PDO(
        $config->get('db.dsn'),
        $config->get('db.user'),
        $config->get('db.pass')
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $pdo;
});

// Closure — conditional factory
$registry->singleton('cache', function (RelayRegistry $r) {
    return match ($r->make('config')->get('cache.driver')) {
        'redis' => new RedisCache(),
        'file'  => new FileCache(),
        default => new ArrayCache(),
    };
});

$registry->bind(string $key, Closure|string $concrete, array $args = []): static

$registry->bind('validator', Validator::class);

$v1 = $registry->make('validator');
$v2 = $registry->make('validator');
// $v1 !== $v2  — completely independent instances

$auth = $registry->make('auth');

if ($registry->has('payment')) {
    $gateway = $registry->make('payment');
}

$registry->forgetInstance('date');
$registry->singleton('date', Date::class, ['America/New_York']);

// Next make('date') builds a fresh instance with the new args

// Auth::__construct(Session $session, Config $config)
// Both 'session' and 'config' are already in the registry → auto-wired

$registry->singleton('session', Session::class);
$registry->singleton('config',  Config::class);
$registry->singleton('auth',    Auth::class);   // Session and Config injected automatically

// Mailer::__construct(Config $config, string $driver)
// Config is in the registry; 'smtp' cannot be auto-wired
$registry->singleton('mailer', Mailer::class, ['smtp']);



namespace YourPackage;

use Laika\Relay\RelayProvider;

class YourRelayProvider extends RelayProvider
{
    public function register(): void
    {
        // Bind your services here
        $this->registry->singleton('your-service', YourService::class);
    }

    public function boot(): void
    {
        // Use other services here — everything is registered by now
        $config = $this->registry->make('config');
        $this->registry->make('your-service')->configure($config->get('your.key'));
    }
}

public function register(): void
{
    // ✅ Correct
    $this->registry->singleton('payment', PaymentGateway::class);
    $this->registry->bind('payment.invoice', Invoice::class);

    // ❌ Wrong — 'config' may not be registered yet
    $key = $this->registry->make('config')->get('payment.key');
}

public function boot(): void
{
    // ✅ Config-driven setup
    $config  = $this->registry->make('config');
    $gateway = $this->registry->make('payment');
    $gateway->setApiKey($config->get('payment.stripe_key'));

    // ✅ Attach event listeners
    $events = $this->registry->make('events');
    $events->listen('order.placed', SendPaymentRequestListener::class);

    // ✅ Register routes
    Http::group('/payment', function () {
        Http::post('/charge',  'PaymentController@charge');
        Http::post('/webhook', 'PaymentController@webhook');
    });
}

use Laika\Relay\ProviderRegistry;

$providers = new ProviderRegistry($registry);

// Register accepts class string or instance
$providers->register(CoreRelayProvider::class);
$providers->register(new PaymentRelayProvider($registry));

// Boot all providers after all register() calls
$providers->boot();

if ($providers->has(PaymentRelayProvider::class)) {
    // ...
}



use Laika\Relay\Relay;
use Laika\Relay\RelayRegistry;
use Laika\Relay\ProviderRegistry;
use Laika\Relay\Relays\CoreRelayProvider;

// 1. Build the container
$registry  = new RelayRegistry();

// 2. Build the provider manager
$providers = new ProviderRegistry($registry);

// 3. Register the Laika core provider (always first)
$providers->register(CoreRelayProvider::class);

// 4. Register providers declared in config/app.php
foreach (config('app.providers') as $providerClass) {
    $providers->register($providerClass);
}

// 5. Boot all providers (runs after all register() calls are complete)
$providers->boot();

// 6. Wire the registry into the Relay system
Relay::setRegistry($registry);

return [
    'providers' => [
        // Third-party packages
        Acme\LaikaPayment\PaymentRelayProvider::class,
        Acme\LaikaBarcode\BarcodeRelayProvider::class,
    ],
];



namespace Acme\LaikaPayment;

use Laika\Relay\RelayProvider;

class PaymentRelayProvider extends RelayProvider
{
    public function register(): void
    {
        $this->registry->singleton('payment',         PaymentGateway::class);
        $this->registry->singleton('payment_webhook', WebhookHandler::class);
        $this->registry->bind('payment_invoice',      Invoice::class);
    }

    public function boot(): void
    {
        $key = $this->registry->make('config')->get('stripe_key');
        $this->registry->make('payment')->setApiKey($key);
    }
}



namespace Acme\LaikaPayment\Relay;

use Laika\Relay\Relay;

/**
 * @method static string charge(int $amount, string $currency)
 * @method static bool   verify(string $token)
 * @method static array  history(int $limit = 10)
 */
class Payment extends Relay
{
    protected static function getRelayAccessor(): string
    {
        return 'payment';
    }
}



declare(strict_types=1);

namespace Laika\Relay\Relays;

use Laika\Relay\Relay;

/**
 * @method static bool   attempt(array $credentials)
 * @method static bool   check()
 * @method static bool   guest()
 * @method static mixed  user()
 * @method static void   logout()
 */
class Auth extends Relay
{
    protected static function getRelayAccessor(): string
    {
        return 'auth';
    }
}

use Laika\Nav\Helper\Item;
use Laika\Nav\Builder;

/**
 * @method static Item|Builder  end()
 * @method static Item[]        all()
 * @method static Item|null     find(string $name)
 */

// ✅ Correct — imports the Relay proxy
use Laika\Service\StaffAuth;
use Laika\Service\ClientAuth;
use Laika\Service\Config;
...

if (Auth::check()) {
    $name = Config::get('app', 'name');
    Session::set('last_page', '/dashboard');
}

// ❌ Wrong — imports the real class, static calls fail
use Laika\Core\Auth\Auth;

Auth::check(); // Fatal: Non-static method cannot be called statically

// Direct registry access — no Relay class needed
$session = Relay::getRegistry()->make('session');
$session->set('user_id', 42);

// Entire chain — first call is static, rest are instance
Date::now()
    ->setTimezone('Asia/Dhaka')
    ->modify('+7 days')
    ->setFormat('d M Y')
    ->format();

Date::fromFormat('d/m/Y', '01/04/2025')
    ->toUtc()
    ->toIso8601();

Date::setTimestamp(time())
    ->modify('+1 hour')
    ->humanDiff();



namespace App\Middleware;

use Laika\Core\Auth\Auth as AuthService;
use Laika\Service\Auth;

class AdminMiddleware
{
    public function handle(): void
    {
        Auth::swap(new AuthService(guard: 'admin', table: 'admins'));
        // All subsequent Auth:: calls now resolve against the admin guard
    }
}

Relay::getRegistry()->forgetInstance('auth');
Relay::getRegistry()->singleton('auth', AuthService::class, ['admin', 'admins']);

use Laika\Service\Auth;

protected function setUp(): void
{
    $mock = $this->createMock(\Laika\Core\Auth\Auth::class);
    $mock->method('check')->willReturn(true);

    Auth::swap($mock);
}

protected function tearDown(): void
{
    Auth::clearResolvedInstance();
}

public function test_dashboard_

use Laika\Relay\Relay;
use Laika\Relay\RelayRegistry;

protected function setUp(): void
{
    $testRegistry = new RelayRegistry();
    $testRegistry->instance('auth',    $this->createMock(Auth::class));
    $testRegistry->instance('session', $this->createMock(Session::class));
    $testRegistry->instance('config',  $this->createMock(Config::class));

    Relay::swapRegistry($testRegistry);
}