构建应用程序+ JSON API的Laravel

问题描述:

我打算建立一个Laravel Web应用程序。到目前为止这么好,但它也需要一个JSON RESTful API。构建应用程序+ JSON API的Laravel

这是什么最好的方法呢?我应该建立一个单独的Laravel API和Laravel客户端,还是最好有一个同时具有JSON和HTML表示的应用程序?

有可能受益于分离两个收获,但我实在看不出他们在这一点上。但是缺点是显而易见的,必须维护两个代码库并且必须在客户端实现REST消费功能。

任何其他选择了吗?优点和缺点?

我会选择分离。我喜欢这样的方法:

//routes.php 
Route::group([], function() 
{ 
    Route::match(['get', 'post'],'/', ['as' => 'homepage', 'uses' => '[email protected]']); 
    //other frontend routes 
}); 

Route::group(['namespace' => 'Admin'], function() 
{ 
    Route::match(['get', 'post'],'/admin', ['as' => 'admin', 'uses' => '[email protected]']); 
    //other admin/backend routes 
}); 

Route::group(['namespace' => 'Rest'], function() 
{ 
    Route::match(['get', 'post'],'/rest', ['as' => 'rest', 'uses' => '[email protected]']); 
    //other rest routes 
}); 

Controllers文件夹中的前端控制器。 控制器/管理员文件夹中的管理员控制器。 在控制器/休息文件夹中休息的控制器。

命名空间的一切。然后,您可以将其全部保存在同一个应用程序中。维护2个代码库没有意义,因为您必须在2个地方重复您的业务逻辑。

在你的路线,那么你就可以做到这一点

Route::controller('user', 'UserController'); 

Route::group(['prefix' => 'api', 'namespace' => 'Api'], function() { 
    Route::controller('user', 'Api\UserController'); 
}); 

另外,不要写你的业务逻辑在控制器中。改为使用命令(在Laravel 5.1中称为作业)和repositories

假设你有一个创建用户功能。然后你将有一个相应的命令/作业类。

namespace App\Jobs; 

use App\Repositories\UserRepository; 
use App\Jobs\Job; 
use Illuminate\Contracts\Mail\Mailer; 
use Illuminate\Queue\SerializesModels; 
use Illuminate\Queue\InteractsWithQueue; 
use Illuminate\Contracts\Bus\SelfHandling; 
use Illuminate\Contracts\Queue\ShouldQueue; 

class CreateUser extends Job implements SelfHandling, ShouldQueue 
{ 
    use InteractsWithQueue, SerializesModels; 

    protected $user; 

    public function __construct(UserRepository $user) 
    { 
     $this->user = $user; 
    } 

    public function handle(Mailer $mailer) 
    { 
     // logic to create user 
    } 
} 

,你会在你的UserController

public function postCreateUser() 
{ 
    // validate request 

    $this->dispatch(new CreateUser($inputData)); 

    // return view 
} 

,然后你Api\UserController

public function postCreateUser() 
{ 
    // validate request 

    $this->dispatch(new CreateUser($inputData)); 

    // return JSON output 
} 
使用