我只是要表明我的意思,我想知道它是否是良好的编码习惯,还是应该尽量避免它?
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();
}
}
请理解,此代码不是用于任何用途,它只是一个更合乎逻辑的小例子,我没有在这里发布。
答案 0 :(得分: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';
}
}
然后接受在Query :: connect方法中实现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();
}
}