douquanhui5735
2012-08-06 14:26 阅读 45
已采纳

PHP OOP连接到MYSQL(构造函数与传递实例)的效率

I've been wondering about the effiency of OOP connections. The example structure is shown below. Each class seperated by folder and class name. For example:

/mysql/mysql.class.php //holds general connect and disconnect functions
/mysql/query.class.php //holds all the queries made to the db (uses basic mysql ^ )
/library/application.class.php //holds all the algorithms (uses queries to db ^ )

When it comes to executing an algorithm, the application.class.php calls upon query.class.php (when it needs to query) which calls mysql.class.php for a connection.

Which one of these two ways is correct (if any or both)? Is there a simpler and more efficient way of doing this?

Here is the same way of doing two things (Which is more efficient??) :

require_once('/mysql/mysql.class.php ');
require_once('/mysql/query.class.php ');

$mysqlClass = new MYSQL();
$queryClass = new Query();

class Application {                
  public function getVar() {         
    $param = foo;         
    $db = $mysqlClass->connect(); //connection to mysql
    $queryClass->callsomequerymethod($db, $param); //pass the db connection to function
  } 
} 

VS

class Application {     
  private $db;      
  public function __construct(DatabaseConnection $db, QueryClass $queryclass){
    $this->db = $db;     
  }           
  public function getVar() {         
    $param = foo;         
    $db = $this->db;
    $queryclass->callsomequerymethod($db, $param);
  } 
} 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    douzhuo5671 douzhuo5671 2012-08-06 14:29

    Can't comment on efficiency, but the second method would be better since the variables are neatly scoped within the class that uses them, as opposed to lying in the global namespace.

    A further modification I would make is move the require statements within the constructor so that those files are included only when the class that uses them (in your case Application) is instantiated.

    点赞 评论 复制链接分享

相关推荐