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

时间:2013-06-10 23:53:53

标签: php laravel controller

我有这条路线: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!'
    }

}

4 个答案:

答案 0 :(得分:36)

您可以使用(仅限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()中,您可以根据需要传递参数。

答案 1 :(得分:27)

neto中的Call a controller in Laravel 4

使用IoC ...

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

例如:

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

你也可以提供参数

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

答案 2 :(得分: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创建所有控制器共享的常用功能。请查看commonFunction中的BaseController以及它在两个控制器中的使用方式。

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

}

答案 3 :(得分:8)

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

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

这应该适用于L5.1