2017-08-10 83 views
0

我有多个控制器,有多种方法,它们都返回视图。Laravel重新使用控制器逻辑

class PageController extends Controller { 
    public function index() 
    { 
     // do lots of stuff 
     return view('view.name', $lotsOfStuffArray); 
    } 

    public function list() 
    { 
    //...and so on 
} 

我现在需要创建一个API,它执行许多相同的逻辑,上述方法的,但返回JSON输出,而不是:

class PageApiController extends Controller { 
    public function index() 
    { 
     // do lots of the same stuff 
     return $lotsOfStuffCollection; 
    } 

    public function list() 
    { 
    //...and so on 
} 

什么是完成最好的办法这不需要将代码从一个控制器复制并粘贴到另一个控制器上?

我试过把大量逻辑添加到性状和我的口才车型使用它们,但仍然需要我从控制器复制和粘贴代码到控制器。我也应该注意到,因为我有很多很多方法,所以检查expectsJson()并返回响应是不可行的。

是否已经存储在一个父类的逻辑,然后创建一个子控制器,以期和使用JSON响应子控制器响应一个好主意?

回答

3

你可以抽象的逻辑业务类别。我have answered a similar question

你的PageController,PageAPIController和PageService。

class PageService { 
    public function doStuff() 
    { 
     return $stuff; 
    } 
} 

class PageController extends Controller { 
    public function index() 
    { 
     $service = new PageService(); 
     $stuff = $service->doStuff(); 
     return $stuff; 
    } 

} 

class PageAPIController extends Controller { 
    public function index() 
    { 
     $service = new PageService(); 
     $stuff = $service->doStuff(); 
     return $stuff->toJSON(); 
    } 

    protected function toJSON(){ 
     //You could also abstract that to a service or a trait. 
    } 

} 
+0

@Enstage请接受,如果它回答您的问题 – Wistar

+1

我知道该怎么做,不用担心;)只是尝试了一下,我探索如何在我的环境中实现此之前,我接受。 – Enstage

+0

@Enstage不用担心。 – Wistar