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

报告相同问题?