We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to forward from static component method ? - Dispatcher

Hi, I created a component in my libraries path that returns an instance of a specific object type depending on the parameter given (factory). The purpose of this class is that it allows me to implement only one action an create the needed objects dynamicly based on the parameter of the url.

If a not defined parameter is given, the method shall forward to my show404 action. While this kind of forward does work in the NotFoundPlugin of Vokuro, here it does not and I just can't get it to work.

<?php

namespace Prototype\Libraries;

use Phalcon\Mvc\User\Component;
use Prototype\Libraries\Objects\ClassA;
use Prototype\Libraries\Objects\ClassB;
use Phalcon\Di;

class ObjectFactory extends Component
{
    public static function createObject($URLParam) 
    {
        switch ($URLParam) {
            case 'a':
                return new ClassA();
            case 'b':
                return new ClassB();
            default:
                Di::getDefault()->getDispatcher()->forward(
                    [
                        'controller' => 'errors',
                        'action'     => 'show404'
                    ]
                );
                return false;
        }
    }
}

Note: I don't want to use redirect here, since the user shall have to possibility to correct the URL called.



1.5k

Okay if I pass the dispatcher as a parameter from the controller it works. Can someone explain why this does not work with the static Di?

public static function createObject($URLParam, $dispatcher) 
{
    switch ($URLParam) {
        case 'a':
            return new ClassA();
        case 'b':
            return new ClassB();
        default:
            $dispatcher->forward(
                [
                    'controller' => 'errors',
                    'action'     => 'show404'
                ]
            );
            return false;
    }
}


32.2k
Accepted
answer

Hi it's because the Di::getDefault()->getDispatcher() call internally the get() in other words create a new instance of dispatcher, you have to use Di::getDefault()->getShared('dispatcher') insteand

Good luck



1.5k

Thank you so much!