从另一个控制器内部调用方法

时间:2015-04-20 14:38:38

标签: laravel methods controller external laravel-5

是否可以从Laravel 5中另一个控制器内的一个控制器调用方法(无论用于访问每个方法的http方法)?

2 个答案:

答案 0 :(得分:18)

我就是这样做的。使用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();
    }
}

另请查看Laravel中Command的概念。它可能比上述方法更灵活。

答案 1 :(得分:0)

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;
    }
}