laravel 从一个控制器内部调用另一个方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29750913/
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
Call a method from one controller inside another
提问by Paulo Coghi - Reinstate Monica
Is it possible to call a method from one controller inside another controller in Laravel 5 (regardless the http method used to access each method)?
是否可以从 Laravel 5 中的另一个控制器内部的一个控制器调用一个方法(不管用于访问每个方法的 http 方法)?
回答by Sean Fahey
This is how I have done it. Use the use
keyword to make the OtherController available. Then you can call a method from that class on instantiation.
我就是这样做的。使用use
关键字使OtherController 可用。然后,您可以在实例化时从该类调用方法。
<?php namespace App\Http\Controllers;
use App\Http\Controllers\OtherController;
class MyController extends Controller {
public function __construct()
{
//Calling a method that is from the OtherController
$result = (new OtherController)->method();
}
}
Also check out the concept of a Commandin Laravel. It might give you more flexibility than the method above.
还可以查看Laravel 中命令的概念。与上述方法相比,它可能会给您带来更大的灵活性。
回答by prince
use App\Http\Controllers\TargetsController;
// this controller contains a function to call
class OrganizationController extends Controller {
public function createHolidays() {
// first create the reference of this controller
$b = new TargetsController();
$mob = 9898989898;
$msg = "i am ready to send a msg";
// parameter will be same
$result = $b->mytesting($msg, $mob);
log::info('my testing function call with return value' . $result);
}
}
// this controller calls it
class TargetsController extends Controller {
public function mytesting($msg, $mob) {
log::info('my testing function call');
log::info('my mob:-' . $mob . 'my msg:-' . $msg);
$a = 10;
return $a;
}
}