Nitu Dhaka
Nitu Dhaka

Reputation: 1320

Symfony2: calling a function of another controller

The directory structure is

AppBundle/api/CartController

There is a function defined in CartController.php as onlinecoupontrancation($params).

I need to call this function from AppBundle/api/MerchantController.php. I tried

$this->forward('AppBundle:api/Cart:onlinecoupontrancation', $param);

But it is giving error 404. Any clue for this? Thanks in advance.

Upvotes: 1

Views: 1669

Answers (1)

Rooneyl
Rooneyl

Reputation: 7902

If it is a shared function between two controllers, why not create a shared service class that both controllers use?

For example, CartFunctions.php

<?php
// src/AppBundle/Classes/CartFunctions.php
namespace AppBundle\Classes\CartFunctions;

class CartFunctions
{
    
    public function __construct()
    {
        // optional DI of other things if required
    }
    
    private function onlinecoupontrancation($params)
    {
        $foo = true;
        // whatever you want to do

        return $foo;
    }
}

Create this as a service, instructions here Something like;

app/config/services.yml

services:
    cart.functions:
        class:        AppBundle\CartFunctions
        arguments:    []

So in your controllers;

public function cartAction($params)
{
    // other stuff ...
    $cartFunctions = $this->get('cart.functions');
    $foo = $cartFunctions->onlinecoupontrancation($params);
}

Upvotes: 3

Related Questions