Call other middleware in process method


My problem is: after apply some logic on data comes from DB in HomepageAction, I should call AnotherMiddleware.
AnotherMiddleware is one of 20 different possible middlewares and I don’t want get all of 20 middlewares in HomePageFactory.
also I want send $container to __constructor of AnotherMiddlewareFactory.
Is it good way to solve my problem?


Not 100% sure I understand your use case. But if you don’t want to instantiate all those alternate middleware upfront you could set them up as lazy services and inject an array of them into your HomepageAction for it to choose from.

Other options would be to do a redirect to desired middleware or - particularly if it’s just part of the page that changes - load the desired content via XHR.


This honestly sounds a bit like a router/dispatcher middleware… which is likely one of the few places where you would want to inject the application’s container. We do that in the DispatchMiddleware, too.


for solving this problem I create

// MyAction.php
class MyAction implements ServerMiddlewareInterface
    private $adapter;
    private $flowFactory;

    public function __construct(AdapterInterface $adapter,
                                InsuranceFlowFactoryMethod $flow)
        $this->adapter= $adapter;
        $this->flowFactory = $flow;

    public function process(ServerRequestInterface $request, DelegateInterface $delegate)
        $command='BuildingBoard'; // ----> comes from database <----
        $flow = $this->flowFactory->create($command);
        return $flow->process($request, $delegate);

class InsuranceFlowFactoryMethodFactory
    public function __invoke(ContainerInterface $container)
        return new InsuranceFlowFactoryMethod(

class InsuranceFlowFactoryMethod
    private $configFolder;
    private $adapter;

    public function __construct(string $configFolder, AdapterInterface $adapter)
        $this->configFolder = $configFolder;
        $this->adapter = $adapter;

    public function create($command)
        $nextMiddleware = $this->getMiddlewareClassName($command);
        $flow = new $nextMiddleware($this->adapter);
        return $flow;

don’t try this at home :wink: