如何使用界面最小化对简单网站的依赖性

时间:2016-01-04 21:17:08

标签: php class oop interface

我想使用database.php的接口,因为数据库对象当前在会话的构造函数中是硬编码的。我在index.php中看到包含database.php的问题,因为我不希望索引依赖于数据库......?

但是因为index.php包含了session.php,我认为会话对象的创建应该留给索引,而不是索引依赖于它在其他地方的创建,比如创建会话对象session.php的底部。我在这里没有看到什么,以及如何使用Database类实现的新创建的iDatabase.php创建最少量的依赖项。提前感谢您,因为我愿意接受任何可以帮助我的建议。

以下是我目前的文件

//index.php
<?php
include('session.php');
$session = new Session();
?>
<html>
...
</html>
//session.php
<?php
include('database.php');

class Session {

    private $db;

    function __construct() {
    $this->db = new Database();
    }
}
?>
//database.php
class Database {
...
}

这就是我想要做的......

//index.php
include('database.php');
include('session.php');
$database = new Database();
$session = new Session($database);
<html>
...
</html>
//session.php

class Session {

    private $db;

    public function __construct(iDatabase $database) {
        $this->db = $database;
    } 
}
//database.php
include('iDatabase.php');

class Database implements iDatabase {
... 
}

0 个答案:

没有答案