从同一个控制器管理视图和api

Jul*_*oro 1 api laravel

我的应用程序存在问题,即"混合",我的意思是"混合"控制器必须管理两个视图和API.

所以,基本上,对于每个控制器,我必须检查:

if $request->wantsJson(){
    ... // Client rendering using Angular, return json
}else{
   // Server rendering Using blade, return view
}
Run Code Online (Sandbox Code Playgroud)

我不喜欢在每个控制器方法中都有条件的事实.

我也不希望有一个带有我所有控制器副本的API文件夹,会有很多重复的代码.

我该怎么办?

Pub*_*ana 6

我建议创建一个单独的类来处理输出ex:class ResultOutput使用方法,output.

因此,在您的控制器中,当您准备输出数据时,只需创建一个ResultOutput类的新实例,并output使用相关数据调用方法.

在ResultOutput类中,注入Request对象,以便根据上述逻辑确定输出方法.

例如:在您的控制器中:

return (new ResultOutput())->output($data);
Run Code Online (Sandbox Code Playgroud)

在ResultOutput类中:

class ResultOutput()
{
    private $type;

    public __construct(Request $request) {
        $this->output = 'view';     
        if ($request->wantsJson()) {
            $this->output = 'json';
        }
    }


    public method output($data) {
        if ($this->type =='view') {
            // return the view with data
        } else {
            // return the json output
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

这样,如果您需要引入新的输出方法(例如:xml),您可以在不更改所有控制器的情况下执行此操作.