Laravel:在不改变url的情况下在另一个控制器中加载方法


Laravel: Load method in another controller without changing the url

我有这条路线:Route::controller('/', 'PearsController');是否有可能在Laravel中获得PearsController从另一个控制器加载方法,因此URL不会改变?

例如:

// route:
Route::controller('/', 'PearsController');

// controllers
class PearsController extends BaseController {
    public function getAbc() {
        // How do I load ApplesController@getSomething so I can split up
        // my methods without changing the url? (retains domain.com/abc)
    }
}
class ApplesController extends BaseController {
    public function getSomething() {
        echo 'It works!'
    }
}

您可以使用(L3 only)

Controller::call('ApplesController@getSomething');

L4中可以使用

$request = Request::create('/apples', 'GET', array());
return Route::dispatch($request)->getContent();

在这种情况下,你必须为ApplesController定义一条路由,就像这样

Route::get('/apples', 'ApplesController@getSomething'); // in routes.php

array()中,如果需要,您可以传递参数。

(by neto in Call a controller in Laravel 4)

使用IoC…

App::make($controller)->{$action}();

,

App::make('HomeController')->getIndex();

,你也可以给参数

App::make('HomeController')->getIndex($params);

你不应该。在MVC中,控制器不应该彼此"交谈",如果它们必须共享"数据",它们应该使用模型来实现,这是在你的应用程序中负责数据共享的类类型。

// route:
Route::controller('/', 'PearsController');

// controllers
class PearsController extends BaseController {
    public function getAbc() 
    {
        $something = new MySomethingModel;
        $this->commonFunction();
        echo $something->getSomething();
    }
}
class ApplesController extends BaseController {
    public function showSomething() 
    {
        $something = new MySomethingModel;
        $this->commonFunction();
        echo $something->getSomething();
    }
}
class MySomethingModel {
    public function getSomething() 
    {
        return 'It works!';
    }
}

编辑

你可以做的是使用BaseController来创建所有控制器共享的公共函数。看看BaseController中的commonFunction,以及它如何在两个控制器中使用。

abstract class BaseController extends Controller {
    public function commonFunction() 
    {
       // will do common things 
    }
}
class PearsController extends BaseController {
    public function getAbc() 
    {
        return $this->commonFunction();
    }
}
class ApplesController extends BaseController {
    public function showSomething() 
    {
        return $this->commonFunction();
    }
}

如果您在AbcdController中并试图访问OtherController中存在的public function test()方法,您可以这样做:

$getTests = (new OtherController)->test();