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 miniconda安装不了
  • ¥20 python代码编写
  • ¥20 使用MPI广播数据遇到阻塞
  • ¥15 TinyMCE如何去掉自动弹出的“链接…”工具?
  • ¥15 微信支付转账凭证,如何解决
  • ¥15 在win10下使用指纹登录时,界面上的文字最后一个字产生换行现象
  • ¥20 使用AT89C51微控制器和MAX7219驱动器来实现0到99秒的秒表计数,有开始和暂停以及复位功能,下面有仿真图,请根据仿真图来设计c语言程序
  • ¥15 51单片机 双路ad同步采样
  • ¥15 使用xdocreport 生成word
  • ¥15 请教怎么用MATLAB求坐标