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

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.

图片转代码服务由CSDN问答提供 功能建议

目录结构

  AppBundle / api / CartController \  n   
 
 

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

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

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

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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);
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报