【问题标题】:Referencing other classes in a class - php在一个类中引用其他类 - php
【发布时间】:2014-12-21 03:19:14
【问题描述】:

假设我有两个 php 类 - Security 类和 Database

安全

class Security {
    public function userPermissions() {
        //use getData() from Database to obtain information 
    }
}

数据库

class Database { 
    public function getData() {
        // some code 
        }
    }

安全类需要使用数据库类获取数据,有很多方法可以实现,但不确定最佳实践。

创建两个like的实例会更好吗?

$db = new Database;
$sec = new Security($db);

然后在Security类中使用构造函数将db的实例传递给它?

或者您会在安全类的 __constructor 方法中创建一个新实例吗?

如果有任何最佳做法,我将不胜感激。

【问题讨论】:

  • 我个人的看法是让getData()受保护并使用继承并通过安全类构造函数访问它
  • 使用 PHP 的 Reflection CLass API 这个 api 将完成依赖注入的技巧。

标签: php class oop methods


【解决方案1】:

创建两者的实例,然后在 Security 类中使​​用构造函数将 db 的实例传递给它

您描述的方法称为Dependency injection,从架构的角度来看,它通常是更适合您的案例的解决方案。

【讨论】:

  • 这很有意义。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多