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

Framework Laravel Package

spiral/framework

Spiral Framework is a high-performance, long-running full-stack PHP framework built for RoadRunner. PSR-compliant components, resident memory kernel, and native support for queues, GRPC, WebSockets, and background workers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer create-project spiral/app my-app
    

    Or add to an existing Laravel project via:

    composer require spiral/framework
    
  2. First Use Case:

    • Replace Laravel’s index.php with Spiral’s public/index.php (if using standalone).
    • For Laravel integration, use the spiral/sapi-bridge to proxy requests:
      use Spiral\Sapi\Bridge\Laravel\SapiBridge;
      
      $bridge = new SapiBridge();
      $bridge->run();
      
  3. Key Entry Points:

    • Kernel: config/app.php (Spiral’s equivalent of Laravel’s AppServiceProvider).
    • Routing: Define routes in src/Http/Controller/Route.php (or via annotations).
    • CLI: Run commands via php spiral [command] (e.g., spiral scaffolder:controller).
  4. First Command: Generate a controller:

    php spiral scaffolder:controller User --action=list --action=show
    

Implementation Patterns

Core Workflows

  1. Dependency Injection (DI):

    • Annotations: Use @Inject for constructor injection (e.g., @Inject private Database $db).
    • Attributes: Prefer PHP 8 attributes for type-hinted services:
      #[Inject]
      private Queue $queue;
      
    • Scopes: Leverage isolated scopes for jobs/queues:
      $this->container->runInScope(ContainerScope::QUEUE, fn() => $job->handle());
      
  2. Routing:

    • Annotations:
      #[Route("users", methods: ["GET"])]
      public function listUsers(): Response
      {
          return new Response("Users list");
      }
      
    • Groups:
      $router->group("/api", function (Router $router) {
          $router->get("/users", [UserController::class, "list"]);
      });
      
  3. Queue Jobs:

    • Define handlers with @Job:
      #[Job]
      class SendEmailJob implements JobInterface
      {
          public function __construct(private string $email) {}
      
          public function run(): void
          {
              // Logic here
          }
      }
      
    • Dispatch via QueueInterface:
      $this->queue->dispatch(new SendEmailJob("user@example.com"));
      
  4. Bootloaders:

    • Extend Bootloader for custom logic:
      class AppBootloader extends Bootloader
      {
          public function init(): void
          {
              $this->provideSingleton(MyService::class);
          }
      }
      
    • Register in config/app.php:
      'bootloaders' => [
          AppBootloader::class,
      ],
      
  5. Scaffolding:

    • Generate CRUD:
      php spiral scaffolder:crud User --namespace=App\\Http\\Controller
      
    • Custom templates: Extend Spiral\Scaffolder\Template\TemplateInterface.
  6. HTTP Middleware:

    • Use annotations:
      #[Middleware(AuthMiddleware::class)]
      class UserController extends Controller
      {
          // ...
      }
      

Integration with Laravel

  1. Service Binding: Bind Laravel services to Spiral’s container:

    $this->container->bindSingleton(Auth::class, fn() => app('auth'));
    
  2. Event Dispatcher: Proxy Laravel events to Spiral’s EventDispatcher:

    event(new UserRegistered($user));
    // Spiral will dispatch via its event system
    
  3. Database: Use spiral/cycle-bridge for Cycle ORM integration:

    $this->container->bindSingleton(DB::class, fn() => Cycle\ORM\ORM::create());
    

Gotchas and Tips

Pitfalls

  1. Memory Leaks:

    • Spiral’s resident memory model requires explicit cleanup for long-lived processes (e.g., WebSockets).
    • Use Spiral\Core\Memory\MemoryManager to monitor leaks:
      $this->memoryManager->collectGarbage();
      
  2. RoadRunner Integration:

    • Ensure roadrunner.json is configured for PHP workers:
      {
        "workers": {
          "php": {
            "pool": "default",
            "memory_limit": "256M"
          }
        }
      }
      
    • Gotcha: Forgetting to start RoadRunner (rr serve) will cause silent failures.
  3. Queue Retries:

    • Retry policies require explicit configuration:
      $this->queue->defineInterceptor(
          RetryPolicyInterceptor::class,
          new RetryPolicy(3, 1000) // 3 retries, 1s delay
      );
      
  4. Annotations vs Attributes:

    • Spiral supports both, but attributes are preferred for PHP 8+:
      // ❌ Legacy (annotations)
      /** @Inject */
      private Database $db;
      
      // ✅ Modern (attributes)
      #[Inject]
      private Database $db;
      
  5. Singleton Scope:

    • Avoid binding singletons to interfaces directly (use concrete classes):
      // ❌ Risky
      $this->container->bindSingleton(LoggerInterface::class, MonologLogger::class);
      
      // ✅ Safer
      $this->container->bindSingleton(MonologLogger::class);
      
  6. Route Caching:

    • Clear cached routes after changes:
      php spiral cache:clear
      

Debugging Tips

  1. Tokenizer Issues:

    • Validate listeners with:
      php spiral tokenizer:validate
      
    • Debug with:
      php spiral tokenizer:info
      
  2. Container Scope:

    • Isolate scopes for jobs/queues to avoid cross-contamination:
      $this->container->runInScope(ContainerScope::QUEUE, fn() => $job->handle());
      
  3. RoadRunner Logs:

    • Check storage/logs/roadrunner.log for worker/queue issues.
  4. Performance:

    • Use Spiral\Debug\Debug for runtime metrics:
      Debug::memoryUsage(); // Check memory spikes
      

Extension Points

  1. Custom Bootloaders:

    • Extend Spiral\Boot\Bootloader to add app-specific logic (e.g., database migrations).
  2. Interceptors:

    • Add middleware to queues/jobs:
      $this->queue->defineInterceptor(MyInterceptor::class);
      
  3. Template Engines:

    • Replace Twig with a custom engine by binding TemplateEngineInterface.
  4. Auth Backends:

    • Implement Spiral\Auth\AuthBackendInterface for custom providers (e.g., OAuth2).
  5. Event Listeners:

    • Use Spiral\Event\EventDispatcher for pub/sub:
      $this->eventDispatcher->listen(UserRegistered::class, [UserNotifier::class, "notify"]);
      

Config Quirks

  1. Environment Variables:

    • Prefix with SPIRAL_ (e.g., SPIRAL_QUEUE_CONNECTION=database).
  2. Debug Mode:

    • Enable via .env:
      APP_DEBUG=true
      
  3. RoadRunner Settings:

    • Configure in roadrunner.json (not .env):
      {
        "server": "http://0.0.0.0:8080",
        "static": "./public"
      }
      
  4. Cache Directories:

    • Default: storage/cache. Override in config/cache.php.

Pro Tips

  1. Scaffolding Shortcuts:

    • Generate a full module:
      php spiral scaffolder:module Admin --namespace=App\\Modules\\Admin
      
  2. Queue Supervision:

    • Use Spiral\Queue\Supervisor to monitor failed jobs:
      $this->queue->supervisor()->retryFailed();
      
  3. GRPC Integration:

    • Define services in src/Grpc/Service/*.proto and use spiral/roadrunner-bridge.
  4. Temporal Workflows:

    • For long-running tasks, use spiral/temporal-bridge:
      $workflow = $this->temporal->startWorkflow(
          new OrderWorkflow($orderId),
          new WorkflowOptions()
      );
      
  5. Testing:

    • Use Spiral\Testing\TestCase for isolated tests:
      use Spiral\Testing\TestCase;
      
      class UserTest extends TestCase
      {
          public function testListUsers()
          {
              $this->get("/users")->assertOk();
          }
      }
      
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope