Call a method from one controller inside another

2019-02-17 02:00发布

问题:

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)?

回答1:

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.

<?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 Command in Laravel. It might give you more flexibility than the method above.



回答2:

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