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