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

Core Laravel Package

openswoole/core

Core PHP library for OpenSwoole, enabling async I/O, coroutines, and fibers for building secure, reliable, high-performance applications. Install via Composer and follow the OpenSwoole docs for usage and APIs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require openswoole/core
    

    Require the autoloader in your Laravel app’s composer.json:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "OpenSwoole\\": "vendor/openswoole/core/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case Initialize OpenSwoole in a Laravel service provider (e.g., AppServiceProvider):

    use OpenSwoole\Core;
    
    public function boot()
    {
        $swoole = new Core\Swoole();
        $swoole->start();
    }
    

    Test with a simple HTTP server:

    $http = new Core\Http\Server("0.0.0.0", 9501);
    $http->on("request", function ($request, $response) {
        $response->end("Hello, Swoole!");
    });
    $http->start();
    

Where to Look First

  • Documentation: Check the OpenSwoole PHP docs for core concepts.
  • Laravel Integration: Explore vendor/openswoole/core/src/ for classes like Swoole, Http\Server, and Coroutine.
  • Laravel-Swoole Packages: For Laravel-specific integrations, consider laravel-swoole (built on this core).

Implementation Patterns

Workflows

  1. Async Task Queues Replace Laravel’s queue system with Swoole’s coroutines for high-throughput tasks:

    use OpenSwoole\Coroutine;
    
    Coroutine::create(function () {
        // Simulate async task
        $result = \App\Services\HeavyTask::process();
        // Store result in DB or cache
    });
    
  2. HTTP Server Integration Use Swoole’s HTTP server alongside Laravel’s routing:

    $http = new Core\Http\Server("0.0.0.0", 9501);
    $http->on("request", function ($request) {
        $response = new Core\Http\Response();
        $laravelResponse = app()->handle(
            $request->get(),
            $request->server()
        );
        $response->end($laravelResponse->getContent());
    });
    
  3. Database with Coroutines Offload database queries to coroutines to avoid blocking:

    Coroutine::create(function () {
        $user = \App\Models\User::find(1);
        // Process data asynchronously
    });
    

Integration Tips

  • Laravel Service Container: Bind Swoole components to Laravel’s container for dependency injection:

    $this->app->singleton(Core\Swoole::class, function () {
        return new Core\Swoole();
    });
    
  • Middleware: Use Swoole’s on("request") to wrap Laravel middleware:

    $http->on("request", function ($request, $response) {
        $laravelRequest = new Illuminate\Http\Request($request->get(), $request->server());
        $laravelResponse = app()->handle($laravelRequest);
        $response->end($laravelResponse->getContent());
    });
    
  • Event Loop: Schedule Laravel jobs in Swoole’s event loop:

    $swoole->loop->addTimer(1000, function () {
        dispatch(new \App\Jobs\SyncData);
    });
    

Gotchas and Tips

Pitfalls

  1. Blocking Calls Avoid synchronous Laravel operations (e.g., Model::all()) in coroutines—they block the event loop. Fix: Use Coroutine::create() or go() for async operations.

  2. Global State Swoole’s coroutines share memory; avoid global variables that mutate across requests. Fix: Use request-scoped bindings or dependency injection.

  3. Laravel’s Service Provider Boot Order OpenSwoole must start after Laravel’s dependencies (e.g., database, cache). Fix: Register Swoole in AppServiceProvider@boot() or a dedicated SwooleServiceProvider.

  4. Error Handling Swoole coroutines swallow exceptions by default. Use Coroutine::create() with a try-catch:

    Coroutine::create(function () {
        try {
            // Risky code
        } catch (\Throwable $e) {
            \Log::error($e);
        }
    });
    
  5. Port Conflicts Ensure the Swoole HTTP server port (e.g., 9501) isn’t used by Laravel’s built-in server. Fix: Configure Laravel’s APP_URL to point to Swoole’s port.

Debugging

  • Log Coroutine IDs: Tag logs with Coroutine::getCid() to trace async flows:

    \Log::info("Coroutine ID: " . Coroutine::getCid(), ['event' => 'task_start']);
    
  • Swoole’s Error Logs: Check /tmp/swoole.log (default path) for low-level errors.

  • Xdebug with Swoole: Disable Xdebug in production; it’s incompatible with Swoole’s async model.

Extension Points

  1. Custom Coroutine Hooks Extend Core\Coroutine to add pre/post hooks:

    Coroutine::addHook('start', function () {
        \Log::debug("Coroutine started: " . Coroutine::getCid());
    });
    
  2. Protocol Servers Use Core\Server\Server to build custom TCP/UDP servers:

    $tcp = new Core\Server\Server("0.0.0.0", 9502, SWOOLE_TCP);
    $tcp->on("receive", function ($server, $fd, $reactorId, $data) {
        $server->send($fd, "Pong!");
    });
    $tcp->start();
    
  3. Redis with Swoole Integrate predis/predis with coroutines for async Redis calls:

    Coroutine::create(function () {
        $client = new \Predis\Client(['scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379]);
        $client->set('foo', 'bar');
    });
    
  4. Laravel Horizon Alternative Replace Horizon with Swoole’s task workers for horizontal scaling:

    $taskWorker = new Core\Server\TaskWorker(4); // 4 processes
    $taskWorker->on("task", function ($server, $taskId, $fromWorkerId, $data) {
        // Process $data asynchronously
    });
    $taskWorker->start();
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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