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

consume API from the main application, without HTTP

Hi all,

I have an application working, with normal MVC pattern, rendering views with full data in it. I created routers and controllers for a new API, in the same app and I want to consume then from my frontendControllers for example, without the need of creating a curl request (wich will create a new process, environment etc each time)

Actually I'm triying with some kind of HMVC paradigm, using this:

    public function indexAction()
    {
        // call to the api
        $result = $this->dispatcher->forward(array(
            'action' => 'edit',
            'controller' => 'index',
            'module' => 'user',
            'namespace' => 'App\User\Controllers\Api'
        )); 

        var_dump($result);
    }

but it lacks the http verbs and the request contents. Any clue of how can I accomplish it?

edited May '15

Actually I just instantiate the Controller and call it.


public function indexAction()
{
    $apiUserService = new App\User\Controllers\IndexController();
    $this->view->users = $apiUserService->allAction();
}

Of course, my Api controllers is totally abstracted from request data, response, etc.. it just returns arrays, and gets data from a simple array in DI where I set all my filtered inputs etc (all this through events).



23.6k
Accepted
answer

And finally what I did was creating a service, completely agnostic wich receives the input data and returns data. I use it from the front controllers as well as from the api controllers. Those controllers manage the instantiation of the service, pass parameters to it and get the response and act according to it's nature.