dos49618 2015-04-19 06: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 04: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部