doupacan2098 2016-05-12 07:21
浏览 15
已采纳

单身人士还是静态? 最好的做法对于PHP?

I built small mvc structure and I also created small basic Dependency Invoker based on Reflection class. My question is which one is best practice for using dependent class. For example I have class Call Request and I will use .

public function method(Request $request);

My Question is how to load Request class

  1. Using Singleton and non static class var

    class Request{
    protected $var;
    }
    
  2. Using New Instance with Static Var

    class Request{
    protected static $var;
    }
    
  • 写回答

2条回答 默认 最新

  • dongpan9760 2016-05-12 07:41
    关注

    The choice between a singleton pattern and a "new instance with static" doesn't really resolves the dependency injection question.

    However I suggest you to use the singleton design pattern to access your Request object.

    Why ?

    • This pattern fits your needs, it respects the "one and unique object instance" for your Request class.
    • Developers should be aware of this structure, that's a proof of sustainability.
    • Encapsulation
    • Design patterns are 99% "best pratices"

    And the dependency injection ?

    From my experience, I suggest you to take a look at the factory design pattern.
    You'll centralize the creation of your objects and the dependencies injection will be a lot easier and cleaner.


    Of course, this is only my way to code, I don't pretend to have the best practices and this should be discussable.

    Hope this will help you.

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

报告相同问题?