php - PHP - 如何将一个索引函数用于两个不同的控制器?

时间:

尝试从其他controller调用index方法:


use ProfileController;



class HomeController {


 public function index()


 {


 ProfileController::index();


 }


}



视图对于这种情况非常适合,你可以在方法中注册Composer,也可以创建自己的服务提供程序,并将它注册到config/app.phpproviders数组。


View::composer(


 ['home', 'profile'],


 'AppHttpViewComposersYourViewComposer'


);



compose方法共享相同的代码:


/**


* Bind data to the view.


*


* @param View $view


* @return void


*/


public function compose(View $view)


{


 $friends = [];


 $friendsID = Person_has_person::select('person2')->where('person1', Auth::user()->id)->get();



 foreach ($friendsID as $friendID)


 {


 $friends[] = User::find($friendID->person2);


 }



 $view->with('friends', $friends);


}



为什么你不让两个不同的Routes指向同一个控制器动作?

比如

Route::get('/home', 'ProfileController@index'); Route::get('/profile', 'ProfileController@index');

例如:

FriendRepository


<?php



namespace AppRepositories;



class FriendRepository


{


 public function getAll($user_id)


 {


 $friends = [];


 $friendsID = Person_has_person::select('person2')


 ->where('person1', $user_id)


 ->get();


 foreach ($friendsID as $friendID) {


 $friends[] = User::find($friendID->person2); 


 }



 return friends;


 }


}



然后在控制器里:

HomeController.php


<?php



namespace AppHttpControllers;



use AppRepositoriesFriendRepository;


use IlluminateHttpRequest;



class HomeController extends Controller


{


 /**


 * @var FriendRepository


 */


 private $friend_repository;



 public function __construct(FriendRepository $friend_repository)


 {


 $this->friend_repository = $friend_repository;


 }



 public function index()


 {


 $friends = $this->friend_repository->getAll(Auth::user()->id);



 return view('home')->with('friends', $friends);


 }


}



ProfileController.php


<?php



namespace AppHttpControllers;



use AppRepositoriesFriendRepository;


use IlluminateHttpRequest;



class ProfileController extends Controller


{


 /**


 * @var FriendRepository


 */


 private $friend_repository;



 public function __construct(FriendRepository $friend_repository)


 {


 $this->friend_repository = $friend_repository;


 }



 public function index()


 {


 $friends = $this->friend_repository->getAll(Auth::user()->id);



 return view('home')->with('friends', $friends);


 }


}



...