PHP code example of idei / usim

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

    

idei / usim example snippets




namespace App\UI\Screens;

use Idei\Usim\UI;
use Idei\Usim\Enums\LayoutType;
use Idei\Usim\Screen;
use Idei\Usim\Components\Container;

class HelloScreen extends Screen
{
    protected function buildBaseUI(Container $container, ...$params): void
    {
        $container
            ->layout(LayoutType::VERTICAL)
            ->padding(20);

        $container->add(
            UI::label('title')
                ->text('Welcome to the UsersManager')
                ->style('h1')
        );

        $container->add(
            UI::button('hello_btn')
                ->label('Hello USIM!')
                ->primary()
                ->action('hello_button_clicked')
        );
    }

    public function onHelloButtonClicked(array $params): void
    {
        $this->toast('Data refreshed!', 'success');
    }
}

// Labels
UI::label('greeting')->text('Hello World')->style('h2')->center();
UI::label('legal_copy')->html('legal.terms-snippet');

// Buttons
UI::button('save')->label('Save')->style('primary')->action('save_form');
UI::button('floating_help')
    ->label('Help')
    ->style('secondary')
    ->position('BOTTOM_RIGHT')
    ->offsets(24, 24)
    ->action('open_help');

// Inputs
UI::input('email')->label('Email')->type('email')->', 'disabled' => true, 'disabled_color' => '#e2e8f0'],
        ['id' => 'settings', 'label' => 'Settings', 'closable' => true],
    ], 'overview')
    ->onTabChange('workspace_tab_changed')
    ->onTabClose('workspace_tab_closed')
    ->tabColors([
        'active_tab_color' => 'var(--ui-surface)',
        'active_tab_text_color' => 'var(--ui-text-strong)',
    ]);

$tabs->add(UI::label('overview_copy')->text('Overview content'), tab: 'overview');
$tabs->add(UI::label('reports_copy')->text('Reports content'), tab: 'Reports');

$container->add($tabs);

class MyScreen extends Screen
{
    protected string $store_username = '';       // persisted in plain text
    protected int $store_page = 1;              // persisted in plain text
    protected string $store_theme = 'light';    // readable by the client
    protected string $store_token_crypt = '';   // persisted encrypted
    protected string $tempValue = '';           // NOT persisted
}

->visible(bool $visible)
->width(string $width)
->padding(mixed $padding)
->margin(mixed $margin)
// ... and many more styling options

// app/UI/Screens/Products/List.php
namespace App\UI\Screens\Products;

use Idei\Usim\Screen;
use Idei\Usim\Components\Container;
use Idei\Usim\UI;

class List extends Screen
{
    protected function buildBaseUI(Container $container, ...$params): void
    {
        $container->add(
            UI::label('title')->text('Products')->style('h1')
        );

        // Add your table, filters, etc.
    }
}

// Public screen (default)
public static function authorize(): bool
{
    return true;
}

// Authenticated users only
public static function authorize(): bool
{
    return self:: return self::

public static function getMenuLabel(): string
{
    return 'My Screen';
}

public static function getMenuIcon(): ?string
{
    return '📊';
}

$menu->screen(UsersManager::class);                          // auto label + icon
$menu->screen(Products\List::class, 'All Products', '📦'); // custom label + icon

protected function postLoadUI(): void
{
    // Update components with current data after state restoration
    $user = Auth::user();
    $this->input_name->value($user->name);
    $this->input_email->value($user->email);
}

// In buildBaseUI:
$container->add(
    UI::button('btn_save')
        ->label('Save')
        ->action('save_item')    // → calls onSaveItem()
);

// Handler:
public function onSaveItem(array $params): void
{
    $name = $params['input_name'] ?? '';
    $email = $params['input_email'] ?? '';

    // Save to database...

    $this->toast('Item saved!', 'success');
}

use Idei\Usim\Events\UsimEvent;

// Emit from anywhere:
event(new UsimEvent('user_logged_in', ['user' => $user]));

// In Menu screen or any other screen:
public function onUserLoggedIn(array $params): void
{
    $user = $params['user'];
    $this->updateMenuForUser($user);
}

// Show a toast notification
$this->toast('Operation successful', 'success');  // types: success, error, info, warning

// Navigate to another URL
$this->redirect('/products');
$this->redirect();           // reload current screen

// Close the currently open modal
$this->closeModal();

// Update modal fields
$this->updateModal([
    'field_name' => ['error' => 'This field is 

UI::label('welcome_copy')
    ->html('emails.verify-email', ['user' => $user]);

UI::container('floating_panel')
    ->position('TOP_RIGHT')
    ->positionMode('fixed')
    ->offsets(16, 16);

t('app.welcome', ['name' => 'Emilio']);

use Idei\Usim\Modals\ConfirmDialog;
use Idei\Usim\Enums\DialogType;

public function onDeleteItem(array $params): void
{
    ConfirmDialog::open(
        caller: $this,
        type: DialogType::CONFIRM,
        title: 'Delete Item',
        message: 'Are you sure you want to delete this item?',
        confirmAction: 'confirm_delete',
        cancelAction: 'cancel_delete',
    );
}

public function onConfirmDelete(array $params): void
{
    // Perform the delete...
    $this->closeModal();
    $this->toast('Item deleted', 'success');
}

$modal = UI::container('my_modal')
    ->parent('modal')
    ->padding('20px');

$modal->add(UI::input('field_a')->label('Name'));
$modal->add(
    UI::button('btn_submit')
        ->label('Submit')
        ->action('submit_modal')
);

use Idei\Usim\DataTable\AbstractTableModel;

class ProductsTable extends AbstractTableModel
{
    public function getColumns(): array
    {
        return [
            ['name' => 'id', 'type' => 'int'],
            ['name' => 'name', 'type' => 'string'],
            ['name' => 'price', 'type' => 'float'],
        ];
    }

    public function getFormattedPageData(int $currentPage, int $perPage): array
    {
        return Product::paginate($perPage, ['*'], 'page', $currentPage)
            ->items();
    }
}

$table = UI::table('products_table');
$dataModel = new ProductsTable($table);
// configure columns, pagination, etc.
$container->add($table);

use Idei\Usim\Enums\AspectRatio;

$uploader = UI::uploader('avatar')
    ->label('Profile Photo')
    ->allowedTypes(['image/*'])
    ->maxFiles(1)
    ->maxSize(2)       // MB
    ->aspect(AspectRatio::_1_1)    // crop ratio
    ->size(1);         // display size

$container->add($uploader);

public function onSaveProfile(array $params): void
{
    if ($filename = $this->uploader_avatar->confirm($params, 'images', $oldFilename)) {
        $user->avatar = $filename;
        $user->save();
    }
}

use Idei\Usim\Enums\AspectRatio;
use Idei\Usim\ValueObjects\Size;

$image = UI::image('post_image')
    ->width(Size::px(640))
    ->placeholderAspect(AspectRatio::_16_9)
    ->placeholderId($post->id)
    ->placeholderColors('#e2e8f0', '#475569')
    ->caption($post->title);

$image = UI::image("post_img_{$post->id}")
    ->src($post->image ?? '')
    ->storage('uploads/images')
    ->placeholderAspect(AspectRatio::_16_9)
    ->placeholderId($post->id);

$ui = uiScenario($this, SomeScreen::class, ['reset' => true]);

$ui->component('btn_submit')->expect('action')->toBe('submit_form');

$response = $ui->click('btn_submit', ['field' => 'value']);
$response->assertOk();
expect($response->json('toast.type'))->toBe('success');

$ui->assertNoIssues();

use App\Models\User;
use App\UI\Screens\Admin\UsersManager;
use Idei\Usim\Contracts\ScreenAuthorizerInterface;
use Mockery;

it('authorizes admin via mock authorizer', function () {
    $user = new User(['id' => 1, 'email' => '[email protected]']);

    $authorizer = Mockery::mock(ScreenAuthorizerInterface::class);
    $authorizer->shouldReceive('can')->with($user, 'users.manage', Mockery::any())->once()->andReturn(true);
    app()->instance(ScreenAuthorizerInterface::class, $authorizer);

    $screen = new UsersManager();
    expect($screen->authorize($user))->toBeTrue();
});

return [
    'front_store_key'           => env('FRONT_STORE_KEY', 'my-app'),
    'screens_namespace' => 'App\\UI\\Screens',
    'screens_path'      => app_path('UI/Screens'),
    'api_url'           => env('API_BASE_URL', env('APP_URL')),
    'upload_disk'       => env('UPLOAD_DISK', 'local'),
    'users'             => [
        'roles' => [
            // admin/user role metadata + seed_user defaults
        ],
    ],
    'i18n'              => [
        'default_locale'  => env('USIM_DEFAULT_LOCALE', env('APP_LOCALE', 'en')),
        'fallback_locale' => env('USIM_FALLBACK_LOCALE', 'en'),
    ],
];

// Use Laravel HTTP client or GuzzleHttp to consume API directly
$response = Http::get(config('usim.api_url') . '/api/ui/admin/dashboard');
$screen = $response->json();

if (isset($screen['agent_context'])) {
    // Agent access to metadata
    $context = $screen['agent_context'];
}

// Automatic — no configuration needed
$events->listen(\Laravel\Octane\Events\RequestReceived::class, function () {
    UIIdGenerator::reset();
});
bash
php artisan usim:install
bash
php artisan migrate
./start.sh [-r]
bash
php artisan usim:discover
bash
php artisan usim:discover
bash
php artisan usim:discover
# Output: Found 12 screens. USIM manifest generated successfully!
bash
php artisan vendor:publish --tag=usim-config