在一个对象中创建一个对象,它是一种很好的编码习惯吗? (PHP)
问题描述:
我只是想说明我的意思,并且我想知道它是好的编码实践还是应该尽量避免它?在一个对象中创建一个对象,它是一种很好的编码习惯吗? (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();
}
}
请大家明白,这个代码是没有任何一种使用的,它是这我不是在这里张贴的东西更符合逻辑的只是一个小例子。
答
是的,这是一个很好的做法,但你可以使其更加灵活:
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();
}
}
换句话说,不,这不是很好的做法。尽可能使用依赖注入和/或接口。 –