2012-07-11 47 views
1

我知道有關於此問題的一些問題已經打開,但我需要一個更具體的示例
和解決方案。PHP OOP問題,舉例

這裏是我的榜樣
databse.class.php

class db{ 
    public function connect($conStr){...} 
} 

func.class.php

func class{ 
    public insert_song(){ 
     //ineed to use the conenct method from database 
     //then I would INERT INTO... 
    } 
} 

問題:
1)宜我需要e還是在func類中擴展db類?
2)如果我需要,db類函數的作用域會保留嗎? (可以說,如果我有一個私有變量出現,會是從出方訪問?)

+0

'func'類的工作是什麼?而對於文件命名,我建議你選擇PSR-0兼容的東西,這樣你就可以使用標準的自動加載器,並且更容易集成其他作者的代碼。 – hakre 2012-07-11 07:55:04

+0

@hakre,你可以看到它的工作是使用數據庫方法和創建歌曲,搜索歌曲等...什麼是自動加載器? – funerr 2012-07-11 07:56:48

+0

http://www.phptherightway.com/#code_style_guide – 2012-07-11 07:57:12

回答

2

由於抽象的一部分,您應該分開的責任爲你的課程。你的Database班應該關心你的Songs(這是你應該如何命名的)班。

如果您Songs類使用Database類,你應該注入它在構造函數如下:

<?php 

class Database { 
    public function connect($conStr) { 
     /* 
     * Connect to database here 
     */ 
    } 
} 

class Songs { 
    private $db; 
    public function __construct(Database $db) { 
     $this->db = $db; 
    } 

    public function insert_song($song) { 
     /* 
     * Now you can use $this->db as your database object! 
     */ 
    } 
} 
3
// changed the class name, func is not good for a class name. 
class Foo { 
    protected $db; 

    public setDb($db) { 
    $this->db = $db; 
    } 

    public insert_song(){ 
     //ineed to use the conenct method from database 
     //then I would INERT INTO... 
     $this->db->insert(...); 
    } 
} 

例子:

// omited the error handling. 
$db = new db(); 
$db->connect(); 
$foo = new Foo(); 
$foo->setDb($db); 
$foo->insert_songs(); 
+0

甚至可以設置構造函數接收'$ db'參數而不是'setDb'。少一行寫:) – Zagor23 2012-07-11 08:31:26

+0

@ Zagor23是的,有兩種方法可以做依賴注入,使用構造函數或setter。兩者都有自己的優點。 – xdazz 2012-07-11 08:36:40

5
  • 不,你不應該要求或擴展數據庫類。
  • 不,私人變量或方法在類之外永遠不可用。受保護的變量僅適用於子類,公共變量是... public。

您可能需要數據庫類位於配置文件中的某個位置,因此您可以隨時隨地實例化數據庫類。但是,因爲您可能只需要數據庫對象的一個​​實例,您可以在配置中將其實例化並使用Dependency injection傳遞它。

這基本上意味着你將數據庫對象傳遞給其他需要的對象。處理數據庫對象的常用方法是使用Constructor injection,儘管setter注入也可以。

你要做的就是類似這樣的東西:

// config: 
$db = new Database; 
$db->setConnectionValues(); 

$fooClass = new Foo($db); 
$fooClass->insertSomething(); 

// fooClass: 
class Foo 
{ 
    private $db; 

    public function __construct(Database $db) 
    { 
     $this->db = $db; 
    } 

    public function insertSomething() 
    { 
     $this->db->query("INSERT"); 
    } 
} 

這可以解決大部分的依賴性問題。