Call a method from one controller inside another

我的梦境 提交于 2019-12-01 01:09:52

问题


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


来源:https://stackoverflow.com/questions/29750913/call-a-method-from-one-controller-inside-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!