複合パターンを使用して、再利用可能な要素を使用してページを作成しています。このために、パターンを駆動するシンプルなインターフェースがあります
interface Ai1ec_Renderable {
/**
* This is the main function, it just renders the method for the element,
* taking care of childrens ( if any )
*/
public function render();
}
一部の要素のみが子を持つことが許可されるため、その動作を追加する抽象クラスを作成しました
abstract class Ai1ec_Can_Have_Children {
/**
*
* @var array
*/
protected $renderables = array();
/**
* Adds a renderable child to the element
*
* @param Ai1ec_Renderable $renderable
*/
public function add_renderable_children( Ai1ec_Renderable $renderable ) {
$this->renderables[] = $renderable;
}
}
したがって、オブジェクトが子を持つことができる場合は、抽象クラスを拡張します。HTML要素の2番目の抽象クラスがあるため、問題が発生します
abstract class Ai1ec_Html_Element {
/**
*
* @var string
*/
protected $id;
/**
*
* @var array
*/
protected $classes = array();
/**
*
* @param $id string
*/
public function set_id( $id ) {
$this->id = $id;
}
public function add_class( $class ) {
$this->classes[] = $class;
}
protected function create_class_markup() {
if (empty( $this->classes )) {
return '';
}
$classes = implode( ' ', $this->classes );
return "class='$classes'";
}
protected function create_attribute_markup(
$attribute_name,
$attribute_value
) {
if (empty( $attribute_value )) {
return '';
}
return "$attribute_name='$attribute_value'";
}
}
問題は、コンポジットのすべてのオブジェクトがインターフェースを実装する必要があり、そのうちのいくつかは最初のクラス ( can_have_children ) のみを拡張し、2 番目のクラスは拡張しない必要があることです (これは、別のレンダリング可能なオブジェクトを構成してジョブを実行する高レベルの抽象化であるためです)。 、それらのいくつかは2番目であるが最初ではなく、それらのいくつかは両方のクラスです。
クラスの設計中に何か間違ったことをしたことがありますか?どうすれば解決できますか? 最も明白な方法は、いくつかのコードを複製するクラスを作成することです
abstract class Ai1ec_Can_Have_Children extends Ai1ec_Html_Element {
/**
*
* @var array
*/
protected $renderables = array();
/**
* Adds a renderable child to the element
*
* @param Ai1ec_Renderable $renderable
*/
public function add_renderable_children( Ai1ec_Renderable $renderable ) {
$this->renderables[] = $renderable;
}
}
これは機能しますが、Can_Have_Children に何かを追加するとコードを複製する必要があるため、何かが正しくないという匂いがします。私は何をすべきか?
PS 特性はありません。私は 5.2 をサポートしています