我正在我的应用程序中设置嵌套资源路由。目前,我有
// in app/routes
Route::resource("users.folders", "FolderController");
// in app/controllers/api/v2
class FolderController extends \BaseController {
public function index($userId)
{
return Response::json( Sentry::getUser()->clients()->find($userId)->folders()->with("resources")->get() );
}
public function show($userId, $id)
{
if( $f = Sentry::getUser()->clients()->find($userId)->folders()->with("resources")->find($id) )
{
return Response::json( $f );
}
return Response::json(["status" => "Not Found"], 404);
}
// ...
}
我总是以同样的方式加载用户,但总是写Sentry::getUser()->clients()->find($userId)
似乎是多余的。有没有办法在__construct
函数中加载正确的用户?
我很想做像
这样的事情class FolderController extends \BaseController {
public function __construct( $userId )
{
$this->user = Sentry::getUser()->clients()->find($userId);
}
public function index()
{
return Response::json( $this->user->folders()->with("resources")->get() );
}
public function show($id)
{
if( $f = $this->user->folders()->with("resources")->find($id) )
{
return Response::json( $f );
}
return Response::json(["status" => "Not Found"], 404);
}
// ...
}
但这会导致异常。
答案 0 :(得分:0)
我认为这不可能,但您可以将此代码移至功能:
private function getUsers($id) {
return Sentry::getUser()->clients()->find($userId);
}
现在可以使用的功能:
return Response::json( $this->getUsers($userId)->folders()->with("resources")->get() );