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条)

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面