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

Api Components Bundle Laravel Package

components-web-app/api-components-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require components-web-app/api-components-bundle
    

    Add to config/app.php under providers:

    ComponentsWebApp\ApiComponentsBundle\ComponentsWebAppApiComponentsBundle::class,
    
  2. Publish Configuration

    php artisan vendor:publish --provider="ComponentsWebApp\ApiComponentsBundle\ComponentsWebAppApiComponentsBundle" --tag="config"
    

    This generates config/api_components.php. Review and adjust:

    • API routes prefix (api_prefix)
    • Default response formats (response_formats)
    • CORS settings (cors_allowed_origins)
  3. First Use Case: Exposing a Component Create a basic component controller:

    namespace App\Http\Controllers;
    
    use ComponentsWebApp\ApiComponentsBundle\Controller\ApiComponentController;
    use Symfony\Component\HttpFoundation\Response;
    
    class MyComponentController extends ApiComponentController
    {
        public function getData(): Response
        {
            return $this->respond([
                'message' => 'Hello from API Components!',
                'data' => ['key' => 'value']
            ]);
        }
    }
    

    Register the route in routes/api.php:

    $router->mount('/my-component', 'App\Http\Controllers\MyComponentController')
        ->methods(['GET'])
        ->bind('my_component');
    
  4. Test the Endpoint

    php artisan serve
    

    Visit http://localhost:8000/api/my-component to see the response.


Where to Look First

  • Configuration: config/api_components.php for bundle settings.
  • Controllers: Extend ApiComponentController for reusable API logic.
  • Documentation: Check src/Resources/doc/ for usage examples (if available).
  • Tests: tests/ directory for integration patterns.

Implementation Patterns

Core Workflows

1. Component-Based API Design

  • Pattern: Treat each reusable UI component (e.g., hero banner, product card) as a separate API endpoint.
  • Example:
    // routes/api.php
    $router->mount('/hero-banner', 'App\Http\Controllers\HeroBannerController')
        ->methods(['GET'])
        ->bind('hero_banner');
    
  • Benefit: Decouples frontend (React/Vue) from backend logic.

2. Response Standardization

  • Use ApiComponentController's respond() method to enforce a consistent response format:
    return $this->respond([
        'success' => true,
        'data' => $componentData,
        'meta' => ['timestamp' => now()->toIso8601String()]
    ]);
    
  • Override getResponseFormat() in your controller to customize formats (e.g., JSON, XML).

3. Request Validation

  • Leverage Symfony Validator for input validation:
    use Symfony\Component\Validator\Constraints as Assert;
    
    public function postData()
    {
        $this->validateRequest([
            'name' => new Assert\NotBlank(),
            'email' => new Assert\Email()
        ]);
        // ...
    }
    
  • Errors are automatically formatted in the response.

4. Authentication & Authorization

  • Integrate with Laravel's built-in auth:
    public function getData()
    {
        $this->authorize('view', $this->componentModel);
        return $this->respond([...]);
    }
    
  • Use middleware for API-wide auth (e.g., auth:api).

5. Dynamic Component Loading

  • Load components dynamically based on user roles or settings:
    public function getDynamicComponent()
    {
        $component = $this->getComponentByUserRole(auth()->user()->role);
        return $this->respond($component->toArray());
    }
    

Integration Tips

Laravel-Specific Integrations

  1. Service Providers Bind custom services to the bundle’s container:

    $this->app->bind(
        ComponentsWebApp\ApiComponentsBundle\Services\ComponentService::class,
        App\Services\CustomComponentService::class
    );
    
  2. Event Listeners Listen to bundle events (e.g., ComponentLoaded) for side effects:

    public function handle(ComponentLoaded $event)
    {
        Log::info("Component {$event->getName()} loaded at {$event->getTimestamp()}");
    }
    
  3. Blade + API Sync Use the API to preload component data for Blade templates:

    // Controller
    public function show()
    {
        $componentData = $this->call('my_component')->getData();
        return view('page', compact('componentData'));
    }
    

Performance Optimization

  • Caching: Cache component responses with Laravel’s cache:
    $data = Cache::remember("component_{$id}", now()->addHours(1), function() use ($id) {
        return $this->getComponentData($id);
    });
    
  • Lazy Loading: Load non-critical components via AJAX:
    // Frontend
    fetch('/api/lazy-component')
        .then(response => response.json())
        .then(data => renderComponent(data));
    

Testing Patterns

  • Unit Tests: Mock ApiComponentController:
    $controller = $this->createMock(ApiComponentController::class);
    $controller->method('respond')->willReturn(new Response('{}'));
    
  • Feature Tests: Test routes with Http::get():
    $response = Http::get('/api/my-component');
    $response->assertStatus(200)->assertJsonStructure(['data']);
    

Gotchas and Tips

Pitfalls

  1. Route Conflicts

    • Issue: Overlapping routes between the bundle and your app.
    • Fix: Use unique route prefixes (e.g., /api/v1/components) and validate with:
      php artisan route:list
      
  2. CORS Misconfiguration

    • Issue: Frontend fails with CORS errors.
    • Fix: Ensure cors_allowed_origins in config/api_components.php includes your frontend URL:
      'cors_allowed_origins' => ['http://localhost:3000', 'https://yourdomain.com'],
      
  3. Response Format Inconsistencies

    • Issue: Mixed response formats (JSON/XML) across endpoints.
    • Fix: Override getResponseFormat() in your controller or enforce it via middleware:
      public function getResponseFormat(): string
      {
          return 'json'; // Force JSON
      }
      
  4. Dependency Injection Issues

    • Issue: Services not injected into controllers.
    • Fix: Ensure the bundle’s service provider is loaded after your app’s providers in config/app.php.
  5. Rate Limiting

    • Issue: API endpoints hit rate limits unexpectedly.
    • Fix: Configure Laravel’s throttle middleware:
      Route::middleware(['throttle:60,1'])->group(function () {
          // Rate-limited routes
      });
      

Debugging Tips

  1. Log Component Loading Enable debug logs for component events:

    // config/logging.php
    'channels' => [
        'single' => [
            'level' => 'debug',
            'handlers' => ['stream'],
        ],
    ],
    

    Check logs for ComponentLoaded events.

  2. Validate Request Payloads Use Laravel’s dd() or dump() to inspect request data:

    public function postData()
    {
        dump($this->request->all()); // Debug payload
        // ...
    }
    
  3. Check Response Headers Inspect headers for CORS or caching issues:

    curl -I http://localhost:8000/api/my-component
    
  4. Bundle-Specific Debugging

    • Command: Run php artisan api-components:debug (if available) to inspect bundle state.
    • Environment: Set APP_DEBUG=true in .env for detailed error pages.

Extension Points

  1. Custom Response Formats Extend the ResponseFormatter service:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->extend(
            ComponentsWebApp\ApiComponentsBundle\Services\ResponseFormatter::class,
            function ($formatter) {
                return new CustomResponseFormatter($formatter);
            }
        );
    }
    
  2. Add New Component Types Create a trait for reusable component logic:

    trait DynamicComponentTrait
    {
        public function getDynamicData()
        {
            return $this->fetchFromDatabaseOrCache();
        }
    }
    

    Use it in controllers:

    class MyComponentController extends ApiComponentController
    {
        use DynamicComponentTrait;
        // ...
    }
    
  3. Hook into the Bundle’s Lifecycle

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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware