PHP类中 要不要把引用的其他类在构造方法中实例

之前的代码 经常是在 __construct 方法中写其他类的new操作,比如 一个写逻辑的类中 有多个方法,这些方法需要调用多个不同model类
为了方便 写成这样,方法中直接用$this-> 调用

class A{

    public function __construct()
    {
        $this->day_model = new Day();
        $this->plan_model = new Plan();
        $this->month_model = new Month();
    }
    
    public function a(){

        $this->day_model->getAbc();
        ....

    }
    
     public function b(){

        $this->day_model->getBcd();
        ....

    }
      public function c(){

        $this->plan_model->getSdf();
        ....
    }
    
}

之前一直这么写,最近看看觉得这样写有问题了, 在使用a()方法的时候,虽然只用了day_model 但是在调用时也要 new plan 和month model,这样会浪费资源吧,如果plan和month中如果有什么错误的话,a方法也不会调用成功,
那这样是不是 就把new的操作写在 需要用到的各个方法里么?

阅读 2.2k
1 个回答

你说提到的问题,如果简单地处理,那么使用单例模式,就能最直接解决你的疑问。

class A
{
    protected static $dayModel;
    
    protected function getDayModel()
    {
        if (!self::$dayModel) {
            self::$dayModel = new Day();
        }
        
        return self::$dayModel;
    }
    
    public function a()
    {
        $this->getDayModel()->getAbc();
        // ...
    }
}

但这很明显不是好的实践,因为这个是硬编码的依赖关系处理(hard-coded dependencies),耦合性太高,不利于单元测试等。依赖关系处理扩展开来讲是个不小的话题,这边就不详细展开了。现在普遍采用的模式是依赖注入(Dependency Injection),主流框架在实践上均使用了服务容器(Service Container),去详细了解之后,很容易就能对你的疑问有答案了。

参考:

  1. PHP之道-依赖注入

  2. Symfony文档-Service Container

  3. 比较简单和流行的Service Container实现:Pimple

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏