Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ui Laravel Package

blast-project/ui

UI package for Blast Project: reusable Laravel front-end components, layouts, and styles to speed up building consistent admin and app interfaces. Includes shared views, assets, and helpers for rapid prototyping and integration with Blast Project apps.

View on GitHub
Deep Wiki
Context7

Implementation Patterns

1. Blade-Driven Component Rendering

Pattern: Replace hardcoded Blade includes with dynamic UI components. Example:

<!-- Before: Static include -->
@include('components.button', ['text' => 'Submit'])

<!-- After: Dynamic registration -->
@ui('primary-button', ['text' => 'Submit'])

Workflow:

  1. Register components in AppServiceProvider:
    UI::register('primary-button', function () {
        return new \BlastProject\UI\Components\Button(
            text: 'Submit',
            type: 'primary'
        );
    });
    
  2. Use @ui() directive in Blade with optional data:
    @ui('primary-button', ['text' => 'Save', 'disabled' => true])
    

2. Doctrine Collections for UI State

Pattern: Use doctrine/collections to manage dynamic UI state (e.g., form data, filters). Example:

use Doctrine\Common\Collections\ArrayCollection;

// Register a component with state
UI::register('user-list', function () {
    $users = new ArrayCollection(User::all());
    return new UserListComponent($users);
});

// Modify state via facade
UI::get('user-list')->getUsers()->filter(fn ($user) => $user->isActive());

Use Cases:

  • Pagination: Replace Laravel paginators with doctrine/collections for UI-specific logic.
  • Form State: Track dirty fields or validation errors in a collection.

3. Service Container Integration

Pattern: Bind UI components to Laravel’s service container for dependency injection. Example:

// In AppServiceProvider
$this->app->bind(\App\Components\Dashboard::class, function ($app) {
    return new Dashboard(
        $app->make(AnalyticsService::class),
        $app->make(UserRepository::class)
    );
});

// Register with UI facade
UI::register('dashboard', \App\Components\Dashboard::class);

Benefits:

  • Reuse existing Laravel DI for UI components.
  • Test components in isolation with mocks.

4. Theming via Config

Pattern: Override UI themes globally via config/ui.php. Example:

// config/ui.php
'themes' => [
    'default' => [
        'colors' => ['primary' => '#3b82f6'],
        'fonts' => ['body' => 'Inter'],
    ],
    'dark' => [
        'colors' => ['primary' => '#60a5fa'],
    ],
],

// Apply theme in Blade
@ui('dashboard', ['theme' => 'dark'])

Implementation:

  1. Extend BlastProject\UI\Contracts\Themeable in your components.
  2. Use UI::setTheme('dark') to switch themes globally.

5. Event-Driven UI Updates

Pattern: Trigger UI updates via Laravel events. Example:

// In an event listener
public function handle(UserUpdated $event) {
    UI::trigger('user-profile', $event->user);
}

// In component
UI::listen('user-profile', function ($user) {
    $this->user = $user;
    $this->render();
});

Use Cases:

  • Real-time updates (e.g., notifications, live search).
  • Decouple UI logic from business events.

6. Multi-Tenant UI Customization

Pattern: Dynamically load tenant-specific UI configurations. Example:

// In a middleware
public function handle($request, Closure $next) {
    $tenant = Tenant::find($request->tenantId);
    UI::setConfig($tenant->ui_config);
    return $next($request);
}

// Tenant config example
[
    'components' => [
        'header' => \App\Components\TenantHeader::class,
    ],
    'theme' => 'tenant-branding',
]

7. Blade Directives for Shortcuts

Pattern: Create custom Blade directives to simplify UI usage. Example:

// In AppServiceProvider
Blade::directive('ui', function ($expression) {
    return "<?php echo app('ui')->render({$expression}); ?>";
});

// Usage in Blade
@ui('dashboard', ['tab' => 'analytics'])

Advanced: Extend with conditional logic:

@ui(auth()->check() ? 'admin-panel' : 'guest-dashboard')

8. API-Driven UI (Hybrid Approach)

Pattern: Use UI components to render API responses. Example:

// Controller
public function show(User $user) {
    return UI::render('user-card', ['user' => $user]);
}

// Blade
@ui('user-card', ['user' => $user])

Benefits:

  • Consistent UI for API and Blade responses.
  • Reuse components across web and API routes.

9. Testing UI Components

Pattern: Test components in isolation using Laravel’s testing tools. Example:

public function test_dashboard_component()
{
    $component = new DashboardComponent(new AnalyticsService());
    $this->assertStringContainsString('Analytics', $component->render());

    // Test with mock dependencies
    $mockService = Mockery::mock(AnalyticsService::class);
    $mockService->shouldReceive('getData')->andReturn([]);

    $component = new DashboardComponent($mockService);
    $this->assertStringContainsString('No data', $component->render());
}

10. Performance Optimization

Pattern: Cache frequently used UI components. Example:

// Register with caching
UI::register('header', function () {
    return Cache::remember('ui.header', now()->addHours(1), function () {
        return new HeaderComponent();
    });
});

// Clear cache when needed
Cache::forget('ui.header');

Gotchas and Tips

Pitfalls

  1. Doctrine Collections Overhead

    • Issue: doctrine/collections can consume significant memory for large datasets.
    • Fix: Use ArrayCollection::toArray() for rendering or switch to native arrays.
    • Tip: Profile memory usage with memory_get_usage() in critical paths.
  2. Blade Caching Conflicts

    • Issue: Cached Blade views may not reflect dynamic UI changes.
    • Fix: Clear Blade cache after UI updates:
      php artisan view:clear
      
    • Tip: Use @verbatim in Blade for dynamic content:
      @verbatim
          @ui('dynamic-content')
      @endverbatim
      
  3. Service Provider Boot Order

    • Issue: UI components may fail to register if the service provider boots too late.
    • Fix: Ensure UIServiceProvider is loaded early in config/app.php.
  4. Missing Type Safety

    • Issue: PHP 7.1+ support lacks type hints, leading to runtime errors.
    • Fix: Add PHPDoc annotations or upgrade to PHP 8.1+:
      /** @var \BlastProject\UI\ComponentInterface */
      $component = UI::get('dashboard');
      
  5. Event Listener Conflicts

    • Issue: UI events may interfere with Laravel’s event system.
    • Fix: Prefix event namespaces:
      UI::listen('ui.user-profile', function ($user) { ... });
      
  6. Configuration Overrides

    • Issue: config/ui.php may be overwritten during updates.
    • Fix: Publish and customize the config:
      php artisan vendor:publish --tag="ui-config"
      
  7. Lazy Loading Pitfalls

    • Issue: Lazy-loaded components may cause delays on first render.
    • Fix: Preload critical components in a route middleware:
      UI::preload('dashboard');
      
  8. Middleware Integration

    • Issue: UI components may not respect middleware (e.g., auth).
    • Fix: Wrap component registration:
      UI::register('admin-panel', function () {
          if (!auth()->check()) abort(403);
          return new AdminPanel();
      });
      

Debugging Tips

  1. Log UI Events Add logging to track UI interactions:

    UI::listen('*', function ($event) {
        \Log::debug("UI Event: {$event->name}", $event->data);
    });
    
  2. Inspect Component State Dump component data for debugging:

    dd(UI::get('dashboard')->getState());
    
  3. Check for Circular Dependencies Use composer why-not blast-project/ui to diagnose dependency conflicts.

  4. Validate Blade Directives Ensure directives are registered before use:

    Blade::if('ui', function () {
        return UI::has('dashboard');
    });
    
  5. Profile Memory Usage Monitor doctrine/collections memory impact:

    $collection = new ArrayCollection(User::all());
    \Log::info('Collection memory: ' . memory_get_usage() / 1024 / 1024 .
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor