首先我们都知道laravel既可以分发web端路由,也可以分发api端路由 但是却如何将api的控制器与web端控制器相互分离,
那么本次就跟大家分享下 如何来将web/api业务处理分开
1 设置 app->Providers:RouteServiceProvider.php
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your web controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $webNameSpace = 'App\Http\Controllers';
/**
* This namespace is applied to your api controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $apiNameSpace = 'App\Http\Apis';
/**
* 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();
//
}
/**
* 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->webNameSpace )
->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->apiNameSpace )
->group( base_path( 'routes/api.php' ) );
}
那么我们看到 map方法下调取两种匹配路由方式 api web 二者主要根据不同的规则分发加载不同的路有文件进行url分发
2 创建对应文件 app->Apis
我们可将web控制器中基类 App\Http\Controllers\Controller.php复制至该文件下
接下来就可以随意的开始你的表演了
---记得在url访问的时候默认加上 api 前缀 http://domain.baidu.com/api/users/list
Laravel 如何加全局辅助函数:
1 找到composer.json文件 autoload 属性下添加
"files": [
"app/Helpers/helpers.php"
]
2 创建对应文件:helpers.php
<?php
if (! function_exists('storage_day_path')) {
/**
* Get the path to the storage folder.
*
* @param string $path
* @return string
*/
function storage_day_path( $file = '')
{
$today = date( 'Y-m-d', time() );
$todayPath = app('path.storage') . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . $today;
if( !is_dir( $todayPath ) || !file_exists( $todayPath ) )
{
mkdir( $todayPath, 0777 );
}
return $todayPath . ( $file? DIRECTORY_SEPARATOR.$file: $file );
}
}
if (! function_exists( 'format_date' ) ) {
/**
* Get the path to the storage folder.
*
* @param string $path
* @return string
*/
function format_date( $datetime = '' )
{
$formatTimeStamp = strtotime( $datetime );
if( is_numeric( $datetime ) )
{
$formatTimeStamp = $datetime;
}
$currYear = date( 'Y', time() );
$formatYear = date( 'Y', $formatTimeStamp );
if( $currYear == $formatYear )
{
return date( 'm-d H:i', $formatTimeStamp );
}
return date( 'Y-m-d', $formatTimeStamp );
}
}
**** 若没生效的话 可以尝试 composer dump-autoload
那么这种子以后,我们的控制器/模型/视图 等等都可以使用该函数进行处理。