Laravel,如何从另一个控制器调用函数 [英] Laravel , how to call a function from another controller

查看:1116
本文介绍了Laravel,如何从另一个控制器调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在名为"UserController"的控制器中有一个具有"getUsers"功能的控制器,在其中要调用名为"getCars"的"CarController"控制器的功能,我有两个选择:

a)将第二个调用设为静态",那么我可以在不实例化类的情况下调用它

b)不要执行静态类的功能,我以这种方式调用它

    $ car_id = 100;
    $ userController = new UserController ();
    $ userController-> getCars ($ car_id);

我不知道哪种方法是最佳做法,或者哪种利弊各有千秋.

我正在使用laravel. 感谢.

解决方案

从另一个控制器调用一个控制器是一种不好的做法,这通常表明您对代码的设计不好,应该考虑采用另一种方法来实现你想要什么.

同样如此,您可以这样做:

app()->call('App\Http\Controllers\CarController@getCars');

如果控制器方法具有参数,则可以将它们作为第二个参数传递:

app()->call('App\Http\Controllers\CarController@getCars', [$param1, $param2]);

I have a controller with the "getUsers" function in a controller called "UserController" , and inside it I want to call a function of the "CarController" controller called "getCars", the two options I have are:

a) Make the second call as "static" , then I can call it without instantiating the class

b) Do not do that function of the static class and I call it in this way

    $ car_id = 100;
    $ userController = new UserController ();
    $ userController-> getCars ($ car_id);

I do not know which is the best practice, or what pros or cons has one or another.

I'm using laravel. Thanxs.

解决方案

It is a bad practice to call a controller from another controller, this usually signals that you have badly designed your code and you should think of a different way to achieve what you want.

None the less, you can do it like this:

app()->call('App\Http\Controllers\CarController@getCars');

If your controller method has parameters you can pass them as the second argument:

app()->call('App\Http\Controllers\CarController@getCars', [$param1, $param2]);

这篇关于Laravel,如何从另一个控制器调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆