douqi3195 2019-08-01 11:10
浏览 39
已采纳

控制器使用其他控制器

Home page display some information from other controllers, like news, article, etc. What is the best way of using other controller's method in one controller?
Suppose there is one controller called HomeController,is it correct to instantiate a Controller class within home controller?
forexample, if I want to use NewsController,instantiate it!?
The following code is just an example, I want to know that what is the best way to access a method or model in another controller?

class HomeController extends Controller
{
    public function index()
    {
        $news_obj = new NewsController();
        $news = $news_obj->getNews();

        $article_obj = new ArticleController();
        $articles = $article_obj->getArticles();

        return view('template',['news'=>$news,'articles'=>$articles]);
    }
}
  • 写回答

5条回答 默认 最新

  • douhui7136 2019-08-01 13:06
    关注

    I agree with @ptrTon on this, I'd suggest adopting a Repository pattern. It may be a bit of a work depending on your app size, but it's defenitely cleaner than instantiating a controller inside another controller.

    Basically with this approach you don't manipulate your model directly but you use instead an object which is, in fact, an extra layer. The main advantage of this is that you can extract common operations and perform them from anywhere not inside the controller, but inside an object which the only responsability is to manage the operations on your models, further separating the responsabilities of your app components. With Laravel you can also add a custom route resolution logic which will inject these repositories in your controllers using the IoC container.

    If you want to take it further, you could create the repository in a way that it behaves as the model which wraps, and extends its functionalities (PHP's magic methods are your friends). Providing a full example in a single answer can be complicated, but I'll link some intresting resources below.

    Repository pattern in Laravel - example

    Decorator pattern - concepts

    Laravel's explicit model binding (see the "customizing resolution logic" section)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程