Laravel: Load method in another controller without changing the url

前端 未结 4 1462
清歌不尽
清歌不尽 2020-12-07 21:20

I have this route: Route::controller(\'/\', \'PearsController\'); Is it possible in Laravel to get the PearsController to load a method from another controller

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 21:51

    You should not. In MVC, controllers should not 'talk' to each other, if they have to share 'data' they should do it using a model, wich is the type of class responsible for data sharing in your app. Look:

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

    EDIT

    What you can do instead is to use BaseController to create common functions to be shared by all your controllers. Take a look at commonFunction in BaseController and how it's used in the two controllers.

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

提交回复
热议问题