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

如何在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 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?