igniphp / framework

Swoole, PSR-15, PSR-7, PSR-11 lightweight modular anti-framework for REST micro-services.
MIT License
265 stars 14 forks source link

How to call registered Module for each request? #36

Closed roquie closed 5 years ago

roquie commented 5 years ago

I would like to use database connection per-request or use connection pool for choosing available before register object in Container.

Any ideas? OnRequestListener does not work for the application.

P.S. My server-app throws a lot of many database errors when parallel requests send from JS (like "General error 7" and "PDO statement not found"). And I'm trying to elegant resolve this problem.

roquie commented 5 years ago

Comes to mind the only solution with a global static object, who is will be called from middleware before $next() and after (close or return back to connection pull).

roquie commented 5 years ago

Hah, Rubber Duck Debugging is working. 🦆

Part of my code with the problem solution:

/**
     * @param \Igni\Application\Http\MiddlewareAggregator|\Igni\Application\HttpApplication $aggregate
     */
    public function provideMiddleware(MiddlewareAggregator $aggregate): void
    {
        /** @var \Illuminate\Container\Container $container */
        $container = $aggregate->getContainer();
        $conf = $container->get(Configuration::class);

        Wait::connection($this->buildDsn($conf), $this->migrate($conf, $container));

        $aggregate->use(function (ServerRequestInterface $request, callable $next) use ($conf, $container) {
            $conn = new PDO($this->buildDsn($conf));
            $conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

            $container->instance(PDO::class, $conn);
            $res = $next($request);
            $conn = null;
            $container->forgetInstance(PDO::class);

            return $res;
        });
    }

Connection pool package will be released later. 😅