我正在使用Laravel路由组通过 api.example.com 和 www.example.com 调用我的控制器
Route::group(['domain' => Config::get('app.api_server')], function ()
{
//API entry point
});
Route::group(['domain' => Config::get('app.web_server')], function ()
{
//Web Application entry point
});
但是,当我向 API 发出请求时,路由组的 Web 应用程序部分中的所有业务逻辑和数据库查询仍然会被执行,这对于我们的用例来说是低效且不必要的。同样的情况,反之亦然,访问 Web 会执行 API 入口点内的所有代码。如何防止不相关的代码执行?
回调函数闭包作为对 Route::group(( 的调用的一部分执行,因此无法阻止回调执行。但是,您可以首先阻止定义路由。
// only create the api routes if the current request is for the api
if (Request::getHttpHost() == Config::get('app.api_server')) {
Route::group(['domain' => Config::get('app.api_server')], function ()
{
//API entry point
});
}
// only create the web app routes if the current request is for the web app
if (Request::getHttpHost() == Config::get('app.web_server')) {
Route::group(['domain' => Config::get('app.web_server')], function ()
{
//Web Application entry point
});
}