douqiang1851 2016-10-10 08:53
浏览 114
已采纳

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

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.

  • 写回答

1条回答 默认 最新

  • douweilaton2762 2016-10-10 09:09
    关注

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵