dos49618 2015-04-19 14:05
浏览 125
已采纳

如何在Laravel中重用控制器代码

I'm new to Laravel (relatively new to the MVC concept in general) and have watched hours of tutorials and read many others, but there is a simple common task that has eluded me: what is the best way to reuse the same basic elements in a system (say, CMS) across controllers?

Scenario:

I have a content management system, and want to use a different controller for each type of function: e.g. a posts controller for manipulating posts, a users controller for managing users, a menu controller for menu items, etc. Most tutorials recommend this type of workflow.

However, in the actual CMS front-end, I have many common elements that are dynamic (come from the DB) but still need to be displayed across all controllers. For example, the menu (comes from the DB), the current user's details (user name and relevant buttons in accordance with permissions), etc. Displaying it to the user (front-end) is easy enough with Blade, but I can't figure out the best way to do this in the back-end.

For example, if each controller separately gets the menu from the DB, that's a (lack of) code reuse nightmare. On the other hand, there doesn't appear to be a central place from where I can insert this code and pass it onto the view across all controllers. I'm sure that the Laravel developers have thought of this extremely common scenario. What is the best way to implement it?

  • 写回答

2条回答 默认 最新

  • doukai2839 2015-04-23 12:03
    关注

    This is exactly what View Composers are for!

    View Composers allow you to register a callback that is executed before a specific view is rendered. Usually you register them in a Service Provider. You can use the existing AppServiceProvider or create a new ComposerServiceProvider for that.

    This would be a very basic example for the view with name menu

    public function boot(){
        View::composer('menu', function($view){
            $menu = DB::table('menu')->get();
            $view->with('menu', $menu);
        });
    }
    

    You could also specify a class that contains the composer logic. Read more about that in the docs

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?