问题描述
我想在侧边栏中生成一个动态菜单并与 Laravel 5.1 中的所有视图共享.
I want to generate a dynamic menu in a sidebar and share with all the views in Laravel 5.1.
喜欢:
- Marks Module
- Langosh Topic
- Content 1
- Content 2
-Nitzsche Topic
- Content 3
- Rolfson Module
虽然所有这些元素都属于另一个名为 course 的实体,我可以在顶部菜单中选择它(用户可以拥有 1 个以上的课程).
Although All this elements belong another entity called course which I can select in the Top menu (users can have more than 1 course).
所以每次我访问课程、模块、主题或内容时,他们都需要告诉侧边栏菜单哪个课程是所有这些孩子的父亲(或祖父)以生成菜单.
So every time that I access, Course, Module, Topic or Content they need to tell the sidebar menu which course is the father (or grandfather) of all of those kids to generate the menu.
在 AppServiceProvider 中,我有视图作曲家,一切正常,但我正在使用会话来获取课程 ID,但我不想知道.
in AppServiceProvider I have view composer and everything's working fine, but I am using sessions to get the course ID, and I don't like to idea.
我如何将 $course 传递给服务提供商,或者还有其他更好的方法吗?
How can I pass the $course to the Service Provider or is there any other better way to do that?
推荐答案
实际上,在这种情况下,您不应该尝试将变量传递给服务提供者.如果需要,可以使用 Laravel 的 容器 来完成,因为它是全局的并且在应用程序中初始化启动.
Actually, you should not try to pass a variable to a service provider in this case. If need comes, this could be done using Laravel's container, because it's global and it's initialized at the application start up.
但由于您只是构建菜单,我建议将菜单构建委托给特定的类.在控制器中创建此类的实例并将其传递给视图.调用它的方法,迭代它的属性以获得菜单结构.
But since you just build menu, I would recommend to delegate menu building to a specific class. Create an instance of this class in controllers and pass it to the view. Call it's methods, iterate it's properties to get menu structure.
如果您有各种应用程序部分提供有关此侧菜单的信息,您可以使用 events将菜单碎片收集在一起.
If you have various application parts providing information about this side-menu, you could utilize events to gather menu pieces together.
这篇关于如何将变量传递给 Laravel 中的服务提供者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!