whitebear
whitebear

Reputation: 12423

Calling function from another controller

I have two controllers

DefaultController

class DefaultController extends Controller
{
    public function indexAction()
    {

ApiController

class ApiController extends Controller
{
    public function getCategoryAction()
    {

Now I want to call getCategoryAction from my DefaultController.

Is it impossible or how can I make it?

Upvotes: 0

Views: 3916

Answers (4)

NHG
NHG

Reputation: 5877

There is forwarding in Symfony2. So, you could do sth like that:

class DefaultController extends Controller
{
    public function indexAction()
    {
        // @var Response $categoryListResponse
        $categoryListResponse = $this->forward('YourBundle:Api:getCategory');
        // ... further modify the response or return it directly
        return $categoryListResponse;
    }
}

Where $categoryListResponse is Response type and represents an HTTP response. So you could $categoryListResponse->getContent() from this response.

Upvotes: 1

TroodoN-Mike
TroodoN-Mike

Reputation: 16165

You can extend ApController controller like this:

class ApiController extends DefaultController
{
    public function yourAction()
    {
         $this->getCategoryAction();
    }
}

Or even better create a MyClass class (if getCategoryAction is going to be reused) register as a service

It all depend what you want to achieve at the end

Upvotes: 0

ponciste
ponciste

Reputation: 2229

you can create you own services and then call them from all the controllers

see Symfony service container

Upvotes: 0

sickelap
sickelap

Reputation: 897

You can configure controller as a service and then use

$this->forward('controller.service.name')->methodOnTheController()

Upvotes: 0

Related Questions