2015-10-19 55 views
0

我只是想說明我的意思,並且我想知道它是好的編碼實踐還是應該儘量避免它?在一個對象中創建一個對象,它是一種很好的編碼習慣嗎? (PHP)

class Connector { 
    public function __constructer ($ip, $port) 
    { 
     $this->socket = fsockopen($ip, $port); // Forgive me, this is simply just example, never going to be used in real-life 

     return $this->socket; 
    } 

    public function getInfo() 
    { 
     // return information which maybe properties of the server the ip is connected too 
    } 
} 

// I just want the class Connector to handle the connection, and keep it running 


// Query will be used for use of the application itself and I don't want to extend connector 

class Query { 
    protected $connection; 

    public function connect ($ip, $port) 
    { 
     $this->connection = new Connector($ip, $port); 
    } 

    public function showInfo() 
    { 
     return echo $this->connection->getInfo(); 
    } 
} 

請大家明白,這個代碼是沒有任何一種使用的,它是這我不是在這裏張貼的東西更符合邏輯的只是一個小例子。

回答

2

是的,這是一個很好的做法,但你可以使其更加靈活:

class Query { 
    protected $connection; 

    public function connect (Connector $connector) 
    { 
     $this->connection = $connector 
    } 

    public function showInfo() 
    { 
     return $this->connection->getInfo(); 
    } 
} 

這就是我們所說的依賴注入。

,甚至更靈活的將使用的接口:

interface ConnectorInterface 
{ 
    public function __construct(array $options); 
    public function showInfo(); 
} 

,然後創建一個或多個類實現接口:

class Connector implements ConnectorInterface 
{ 
    private $ip; 
    private $port; 

    public function __construct(array $options) 
    { 
     $this->ip = $options['ip']; 
     $this->port = $options['port']; 
    } 

    public function getInfo() 
    { 
     return 'basic connector'; 
    } 
} 

class AdvancedConnector implements ConnectorInterface 
{ 
    private $ip; 
    private $port; 
    private $protocol; 

    public function __construct(array $options) 
    { 
     $this->ip = $options['ip']; 
     $this->port = $options['port']; 
     $this->protocol = $options['protocol']; 
    } 

    public function getInfo() 
    { 
     return 'advanced connector'; 
    } 
} 

,然後接受一個實現ConnectorInterface到任何類查詢::連接方法:

class Query { 
    protected $connection; 

    // changed the parameter to ConnectorInterface !!! 
    public function connect (ConnectorInterface $connector) 
    { 
     $this->connection = $connector 
    } 

    public function showInfo() 
    { 
     return echo $this->connection->getInfo(); 
    } 
} 
+1

換句話說,不,這不是很好的做法。儘可能使用依賴注入和/或接口。 –

相關問題