Symfony2:调用另一个控制器的函数

时间:2016-10-10 08:53:04

标签: php symfony

目录结构是

AppBundle/api/CartController

CartController.php中定义的函数为onlinecoupontrancation($params)

我需要从AppBundle/api/MerchantController.php调用此函数。 我试过了

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

但是它给出了错误404.有什么线索吗?提前谢谢。

1 个答案:

答案 0 :(得分:3)

如果它是两个控制器之间的共享功能,为什么不创建两个控制器都使用的共享服务类?

例如,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;
    }
}

将此项创建为服务instructions here 喜欢的东西;

的应用程序/配置/ services.yml

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

所以在你的控制器中;

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