最近因为公司需要开发前端的API,为了后面的管理方便,博主决定在APP目录下跟后台目录平行新建一个模块,专门来做API,由于没有有过往的经历,所以百度了下,但无奈还是找不到,所以就变着法子,看能不能从路由下手,果然一番操作之后,算是成功的新建一个模块。
首页我们先进行基础东西的创建,我们可以在app目录下先创建一个Api目录,底下分别可以创建控制器、业务、数据模型的目录,结构如下:
这样我们便成功的创建了一个模块目录,记得文件的包名如下:
namespace App\Api\Bases;
这是我的基础目录,如果是控制器则是:
namespace App\Api\Controllers;
大家根据目录名定义包名,创建完基础目录之后,我们便开始创建我们的路由,Laravel路由一般都是放在根目录下的routes,我们复制web.php,并重新命名我们想要的路由文件名,我这里命名为apiCustom,路由规则还是跟普通路由规则一样,没什么区别,然后我们修改路由行为文件,我们先打开app\Providers下的RouteServiceProvider.php的文件,为新建的路由创建行为,代码如下:
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
//自定义路由地址【用于前端API】
protected $ApiNamespace = 'App';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
//
parent::boot();
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
$this->mapApiCustomRoutes();
//
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
/**
* 自定义路由
*/
protected function mapApiCustomRoutes()
{
Route::prefix('apiCustom')
->middleware('api')
->namespace($this->ApiNamespace)
->group(base_path('routes/apiCustom.php'));
}
}
在这里我们自定义了mapApiCustomRoutes方法进行路由定义,这里我定义了前缀,避免冲突,后面路由调用必须以apiCustom开头,才能调用我们自定义模块下的方法。
看看我们的路由文件,代码如下:
Route::group(['prefix' => 'ad'], function () {
//获取广告列表
Route::get('getList', 'Api\Controllers\AdController@getList');
});
这里我们指向了AdController控制器下的getList方法,调用的时候路由必须是apiCustom/ad/getList。
这样我们便成功进行了自定义模块,并成功调用,今天就为大家讲到这~