定义结构并继承Interface和/或Abstract Class时,哪一种是最佳做法?为什么?这里有两个例子:
以下是[Interface] – >的示例. [抽象类] – > [类]
Interface DataInterface { public function __construct($connection); public function connected(); public function get(); } Abstract class BaseData implements DataInterface { protected $connection; public function __construct($connection) { $this->connection = $connection; } } class UserData extends BaseData { public function exists() { return is_connected($this->connection); } public function get() { return get_data($this->connection); } } $oUserData = new UserData(new Connection());
这里是[抽象类]的示例 – > [Class]没有界面
Abstract class BaseData { protected $connection; public function __construct($connection) { $this->connection = $connection; } abstract public function connected(); abstract public function get(); } class UserData extends BaseData { public function exists() { return is_connected($this->connection); } public function get() { return get_data($this->connection); } } $oUserData = new UserData(new Connection());
我目前正在创建一个小应用程序(可能会变得更大),并且困惑于如何正确地实现.
顺便提一句,这个声明是__construct()与参数在Interface中有意义吗?
public function __construct($connection);
抽象类定义了一个接口,必须对抽象类的继承者实现. Interface-Construct定义一个必须由实现接口构造的类实现的接口,接口的实现不限于单个接口,而类继承被耦合到单个(抽象)类.
PHP中的接口有意用于允许整个类接口的有限子集的类型映射.没有理由抽象类的接口,因为它们的继承者的接收者的接收者没有使用它们(具有类型暗示或者通过instanceof / is_a的逻辑标识).接口构造的更有价值的好处是可以用替代实现来替换接口的通用实现.
在您的BaseData-Example的情况下,我建议您删除抽象概念,并改用特征和分隔接口.
trait connectionBrokerConstructor { protected $connection; public function isConnected() { return $this->connection instanceof Connection; } public function setConnection(Connection $connection) { $this->connection = $connection; } } interface connectable { public function setConnection(Connection $connection); public function isConnected(); } interface userDataRepositoryInterface { public function get(); } class UserData implements connectable,userDataRepositoryInterface { use connectionBrokerConstructor; public function __construct(Connection $connect = null) { $this->setConnection($connection); } public function get() { return array('something'); } }