How to make a internal REST (or another) call under a MVC application

Hi, i have the following code:

 $router->addGet("/api/user", array(
 'controller' => 'ApiUserController',
 'action'     => 'getUsers',
 )
);

And in the controller ApiUserController:

public function getUsersAction()
{  
// return users in JSON format
}

And in my other controller "UserController", i have:

public function indexAction()
{    
// api/user call via REST
}

How do i call the route "api/user" and get the returning JSON object?

Thanks in advance



30.7k

Hi,

for consumming webservice, guzzle is the right choice: https://github.com/guzzle/guzzle

But doing that inside the same application, ... well, how to say ...

edited Nov '16

You might want to get info about Dispatcher component https://docs.phalconphp.com/en/latest/api/Phalcon_Mvc_Dispatcher.html in Phalcon, and it's method forward():

Forwards the execution flow to another controller/action

Forwarding to other actions

https://docs.phalconphp.com/en/latest/reference/dispatching.html#forwarding-to-other-actions

Phalcon Mvc Dispatcher methods

https://docs.phalconphp.com/en/latest/api/Phalcon_Mvc_Dispatcher.html#methods

If you really want to call your own app via http, that's usually good for AJAX calls from client side and not from one PHP to another PHP as they share the same scope.

curl is preferred lib to handle http client requests.

edited Nov '16

Forward method as wrote above.

Or just put proper code from action to service to return this json, and use service in both actions. This will be faster - each foward is slowing your app down.