douliandan7340 2013-03-23 23:22
浏览 73
已采纳

可以访问PHP MVC框架中的公共类

I have read a lot of SO topics about this already, but still haven't found (or have been able to create) a proper answer.

I am working on a small MVC framework and I want some global class/object that I can call from my controllers (but maybe models too).

There are a couple of routes I can take:

  1. Global variable
  2. Static class/Registry
  3. Dependency injection

The internet seems to agree that the DI is the best route to take. I think I have grasped the idea, but am not comfortable yet. So I want to throw in some background information; I will probably be the only one working on the project, it is a small project, all my controllers extend the main Controller (so I could just load one library like class there).

As a concrete example, I want to have an array of categories. So I started out with putting that array in the CategoryController. But now I noticed I kinda want to use that array in my frontview and in ProductController as well. Obviously I don't want to load all of CategoryController into ProductController. You could also say I could put that array in some kind of configuration or settings file, because of the simpleness of this example, but that's why it's an example. I will probably expand on it with more functionality.

So to summarize: In PHP (specifically inside a MVC model) how can you give your classes (mainly Controllers) access to some kind of common class or other sharable functionality.

  • 写回答

2条回答 默认 最新

  • doufan3408 2013-03-24 20:47
    关注

    Your controllers are created by "something" (usually a front controller). So when the controller is created, you could inject a dependency injection container.

    And in your configuration/bootstrap (before the controller is created), you should add you categories to the container.

    That way you can access the categories from every controller.

    Please note that this is a simple example that doesn't totally fit the spirit of dependency injection. The best solution would be to inject directly the categories (instead of injecting the container). But that can become a lot of work if you generalize that pattern (lots of dependencies to handle in your front controller).

    A solution would be to use a dependency injection framework that could do that for you.

    For example I work on a DI container that lets you inject stuff with annotations (PHP-DI), but there are several other libraries for DI so you have a choice.

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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么