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 can I call controller manually in Micro via Router?

How can I do this right use Micro-routing (or maybe Phalcon\Mvc\Router)?

use Phalcon\Mvc\Micro;
use Phalcon\Loader;

$loader = new Loader();
$loader->registerNamespaces([
    'App\Controllers' => __DIR__ . '/controllers/',
]);
$loader->register();

$app = new Micro();

$app->map(
    '/{contollerName:[a-zA-Z0-9]+}/{actionName:[a-zA-Z0-9]+}',
    function ($contollerName, $actionName) {
        $c = "App\\Controllers\\{$contollerName}Controller";

        $newc = new $c();

        if (is_subclass_of($newc, 'Phalcon\\Mvc\\Controller')) {
            if ($actionName == "show") {
                echo "This is my show!";
                // do smth.
            }
            return $newc->{$actionName}();
        }
    }
);

$app->handle();

Well you can only do HTTP forward to a controller in micro, as there is no dispatcher.

OR you can initiate your controller manually - normal "PHP way". But then again that's just ugly and breaking framework. If that's what you need - you should switch to full Application I guess..

edited Feb '19

Can't I do it any other way? I don't need a complete application, in principle.. Oh. No ideas?

And what about this variant? Can I do it in Micro using Phalcon\Mvc\Router? This code doesn't work for me. Maybe I missed something?

use Phalcon\Mvc\Micro;
use Phalcon\Mvc\Router;

// ...

$app = new Micro();

$router = new Router();

$router->add(
    '/:controller/:action',
    [
        'controller' => 1,
        'action'     => 2,
    ]
);

$app->setService('router', $router, true);

What is the use case? Can You provide concrete example? Possible solution is to add middleware/service and call doWork() on it - decouple complex logic from handler.

edited Feb '19

This is full case. I had some problems, so I created other project for tests. I'm just trying to understand what I missed in the solving the problem.

My test-project doesn’t include anymore, because I don’t understand what I should ad .

What should I add for this to work, but not become a full Application?

Ideally, I wanted to do something like this:

$app->map(
    '/{controller:[a-zA-Z0-9]+}/({id:[0-9]+})?'
    function ($controller, $id) use ($app) {
        $action = 'get';
        $params = [];

        if ($id) {
            $action = 'getOne';
            $params = [ $id ]; 
        }

        // Next, I imagine, that this returns my controller.
        // Otherwise, we get the $app->notFound().
        return [
            'namespace'  => 'App\\Controllers',
            'controller' => $controller,
            'action'     => $action,
            // id falls into the number of parameters of my action.
            'params'     => $params,
        ];
    }
);