如何在 Laravel 5 中的另一个控制器中调用控制器函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31948980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:09:50  来源:igfitidea点击:

How to Call a controller function in another Controller in Laravel 5

laravel

提问by Eric Teixeira

im using laravel 5.

我正在使用 Laravel 5。

I need to call a controller function but this should be done in another controller.

我需要调用一个控制器函数,但这应该在另一个控制器中完成。

I dont know how to do this

我不知道该怎么做

public function examplefunction(){

   //stuff

}

And i have a Route for this function, so at

我有这个功能的路线,所以在

public function otherfunctioninothercontroller(){
// I need examplefunction here
}

how Can i do this?

我怎样才能做到这一点?

回答by shijinmon Pallikal

1) First way

1)第一种方式

use App\Http\Controllers\OtherController;

class TestController extends Controller
{
    public function index()
    {
        //Calling a method that is from the OtherController
        $result = (new OtherController)->method();
    }
}

2) Second way

app('App\Http\Controllers\OtherController')->method();

Both way you can get another controller function.

回答by henriale

If they are not in the same folder, place use namespace\to\ExampleClass;on top of your file, then you are able to instantiate your controller.

如果它们不在同一个文件夹中,请将其use namespace\to\ExampleClass;放在文件的顶部,然后您就可以实例化您的控制器。

回答by martianwars

Let's say I have Controller1 and Controller2. I want to call a function of Controller1 from inside a function placed in Controller2.

假设我有 Controller1 和 Controller2。我想从 Controller2 中放置的函数内部调用 Controller1 的函数。

// Controller1.php
class Controller1 {
    public static function f1()
    {

    }
}

And on the other controller:

在另一个控制器上:

// Controller2.php
use App\Http\Controllers\Controller1;

class Controller2 {
    public function f2()
    {
        return Controller1::f1();
    }
}

Points to be noted:

需要注意的点:

  1. f1() is declared static
  1. f1() 被声明为静态

回答by CodeToLife

A call to a controller from inside another controller is a bad idea. There is no sense of meaning of controllers then. You should just redirect to web.php to save safe whole architecture like this:

从另一个控制器内部调用控制器是一个坏主意。那么控制器的意义就没有了。您应该重定向到 web.php 以保存安全的整个架构,如下所示:

class MyController {
  public function aSwitchCaseFunction(Request $requestPrm){
    ...
    //getting path string from request here
    ...
    switch($myCase){
        case CASE_1:
             return redirect()->route('/a/route/path');
        ....
    }
  }
}