PHP code example of rosalana / core

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

    

rosalana / core example snippets


namespace Rosalana\Core\Providers;

use Rosalana\Core\Contracts\Package;

class Core implements Package
{
    public function resolvePublished(): bool
    {
        // Self determining if the package is published
    }

    public function publish(): array
    {
        // Define what publish and how
        // (CLI will handle publish all automatically)
        return [
            'stuff' => [
                'label' => 'Publish some stuff',
                'run' => function () {
                    // Process publishing...
                }
            ],
        ];
    }
}

use Rosalana\Core\Facades\Trace;

Trace::start('operation.name');

// Your operation logic here

$trace = Trace::finish();

$phase = Trace::phase('sub-operation');

// Your sub-operation logic here

$phase->close(); // Optional manual close

Trace::record(mixed $data = null);
Trace::recordWhen(bool $condition, mixed $data = null);

Trace::fail(\Throwable $error, mixed $data = null);
Trace::exception(\Throwable $error, mixed $data = null);

Trace::decision(mixed $data = null);
Trace::decisionWhen(bool $condition, mixed $data = null);
Trace::recordOrDecision(bool $isDecision, mixed $data = null);

use Rosalana\Core\Facades\Trace;

Trace::capture(function () {
    // Your operation logic here
}, 'operation.name');

$traceArray = $trace->toArray();

Trace::finish()->log('console');

Trace::finish()->log(MyCustomTarget::class);

final class OperationConsole extends Console
{
    public function render(Trace $trace): void
    {
        $this->time($trace->startTime());
        $this->space(); // add space
        $this->token(" --- Operation Trace Log --- ", 'red'); // red token

        $this->newLine(); // move to new line

        $this->token("Operation: {$trace->name()}");
        $this->space();
        $this->dot(5); // add 5 dots
        $this->space();
        $this->arrow('right'); // add arrow pointing right
        $this->space();
        $this->duration($trace->duration());

              -------- ↓ RESULT ↓ ---------

        [12:34:56.789] --- Operation Trace Log ---
        Operation: operation.name ..... → 13.03ms

    }
}

Trace::register([
    'operation.*' => [
        OperationConsole::class,
        OperationFile::class,
        OperationCustom::class,
    ],
    'operation.{create|update}' => [OperationDetailConsole::class],
]);

Trace::targetAlias('custom', Custom::class);

Trace::finish()->log('custom');

$response = Basecamp::get('/users/1');

$response = Basecamp::withAuth()
    ->post('/login', $credentials);

$response = Basecamp::to('app-name')
    ->withAuth()
    ->post('/projects', $payload);

$response = Basecamp::to('app-name')
    ->users()
    ->find(1);

use Rosalana\Core\Services\Basecamp\Service;

class UsersService extends Service
{
    public function find(int $id)
    {
        return $this->manager
            ->withAuth()
            ->get("users/{$id}");
    }

    public function all()
    {
        return $this->manager
            ->withAuth()
            ->get('users');
    }
}

use Rosalana\Core\Services\Basecamp\Manager;

public function register()
{
    $this->app->resolving('rosalana.basecamp', function (Manager $manager) {
        $manager->registerService('users', new UsersService());
    });
}

Basecamp::users()->get(1);
Basecamp::users()->login(['email' => '[email protected]', 'password' => '...']);

Basecamp::timeout(10); // Set custom timeout (seconds)
Basecamp::retry(3); // Retry failed requests (times)
Basecamp::ghost(); // Skip onSuccess callback
Basecamp::version('v2'); // Use specific API version

Basecamp::mock(); // Mock the request (for testing)

Basecamp::to('app-b')
    ->withAuth()
    ->onSuccess(fn ($response) => event(new UserSynced($response)))
    ->onFail(fn ($e) => logger()->error('Sync failed', ['error' => $e->getMessage()]))
    ->get('/users');

Basecamp::fallback(function (\Exception $e) {
    return SomeResponse; // Return a Response instance to recover
})->get('/users');

use Rosalana\Core\Facades\Outpost;

Outpost::to('app-slug');
Outpost::to(['app1', 'app2']);
Outpost::broadcast(); // to all apps except yourself
Outpost::broadcast()->except('app-slug'); // to all except specific app

Outpost::to('app-slug')->request('group.action', [...]);
Outpost::to('app-slug')->confirm('group.action', [...]);
Outpost::to('app-slug')->fail('group.action', [...]);
Outpost::to('app-slug')->unreachable('group.action', [...]);

use Rosalana\Core\Services\Outpost\Message;

$promise = Outpost::to('app-slug')->request('group.action', [...]);

$promise->onConfirm(function (Message $message) {
    // Handle confirmation
});

$promise->onFail(function (Message $message) {
    // Handle failure
});

$promise->onUnreachable(function (Message $message) {
    // Handle unreachable
});

$promise->reject();


public function request(Message $message)
{
    return $message->event(function (Message $message) {
        // Handle the event logic here
    });
}

return $message->event(fn (Message $message) => ...)
    ->queue()
    ->broadcast();

$event->broadcast();
// channel: 'project-link'
// event: 'project.link.confirmed'

$event->broadcast('custom-channel', 'custom-event');

public function request(Message $message)
{
    // You can quickly respond to the sender
    $message->confirm([...]);
    $message->fail([...]);
    $message->unreachable([...]);

    // Check if the message is from a specific app
    $message->isFrom('app-slug');
    $message->payload('key', 'default');

    // Get the promise of the message (for advanced usage)
    // you can override the promises or reject them
    $message->promise();
}

public function register()
{
    Outpost::receive('group.action:status', function (Message $message) {
        // Handle incoming request
    });

    Outpost::receiveSilently('group.action:status', function (Message $message) {
        // Handle incoming request silently
    });
}

Outpost::receive('group.action:status', function (Message $message) {
    return $message->event(function (Message $message) {
        // Handle the event logic here
    })->broadcast();
});

use Rosalana\Core\Services\Outpost\Service;
use Rosalana\Core\Services\Outpost\Message;

class ProjectService extends Service
{
    public function link(string $target, array $payload)
    {
        return $this->manager
            ->to($target)
            ->request('project.link', $payload)
            ->onConfirm(function (Message $message) {
                // Handle confirmation
            });
    }
}

use Rosalana\Core\Services\Outpost\Manager;

public function register()
{
    $this->app->resolving('rosalana.outpost', function (Manager $manager) {
        $manager->registerService('project', new ProjectService());
    });
}

Outpost::project()->link('app-slug', [...]);

App::context(); // scope: __app
App::context()->scope('user.1'); // scope: user.1
App::context()->scope($user); // scope: user.{id}
App::context()->scope([User::class, 1]); // scope: user.1

$scope->get('foo', 'default'); // Get value with default
$scope->put('nested.foo', 'bar'); // Set value
$scope->has('foo'); // Check if key exists
$scope->receive(); // Get all data in the scope

App::context()->all(); // Get full app context
App::context()->raw(); // Get raw Redis data

App::context()->find('user.*', ['role' => 'admin']);

$scope->forget('foo'); // Remove only one attribute
$scope->clear(); // Remove whole scope
App::context()->flush(); // Remove whole context

// In rosalana/roles — without dependency on rosalana/accounts
Event::listen('Rosalana\\Accounts\\Events\\UserLoggedIn', function ($event) {
    // React to user login
});

use Rosalana\Core\Events\ContextUpdated;
use Illuminate\Support\Facades\Event;

Event::listen(ContextUpdated::class, function (ContextUpdated $event) {
    logger("Context updated: {$event->path} in scope {$event->scope}");
});
bash
php artisan rosalana:publish