19

I have this route: Route::controller('/', 'PearsController'); Is it possible in Laravel to get the PearsController to load a method from another controller so the URL doesn't change?

For example:

// 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!'
    }

}
4

4 回答 4

37

您可以使用(仅限 L3)

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()传递参数。

于 2013-06-11T01:16:40.037 回答
27

(由neto在 Laravel 4中调用控制器

使用国际奥委会...

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

例如:

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

你也可以给参数

App::make('HomeController')->getIndex($params);
于 2014-01-05T21:05:58.157 回答
11

你不应该。在 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 来创建所有控制器共享的通用函数。看看commonFunctioninBaseController以及它是如何在两个控制器中使用的。

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

}
于 2013-06-11T00:07:15.330 回答
8

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

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

这应该在 L5.1 中工作

于 2015-11-10T22:36:07.337 回答