php,oop;为不同深度的分类项目选择正确的设计模式,并显示项目链接 简介
你好 我想建立一个大数据结构,如下所示:php,oop;为不同深度的分类项目选择正确的设计模式,并显示项目链接 简介,php,algorithm,oop,design-patterns,data-structures,Php,Algorithm,Oop,Design Patterns,Data Structures,你好 我想建立一个大数据结构,如下所示: [products] .[cat_1] .[cat_1.1] .[item-A] //type 1 .[item-B] //type 1 . ... .[cat_1.2] .[item-X] //type 2 .[cat_2] .[item-Y] //type 3 到目前为止还不错 目标 由于网站应为目录类型,URL应为: www.e
[products]
.[cat_1]
.[cat_1.1]
.[item-A] //type 1
.[item-B] //type 1
. ...
.[cat_1.2]
.[item-X] //type 2
.[cat_2]
.[item-Y] //type 3
到目前为止还不错
目标
由于网站应为目录类型,URL应为:
www.example.com/products/cat_1/../cat_Y/
该URL上的行为应该是:向所有子项(仅项目或仅子组)显示其预览图像和指向example.com/products/cat_1/../cat_Y/item-X
的超链接。
项目类型当然不同
我所做的
班级
我基于复合模式实现了该结构,因此节点和叶具有一个公共基类,在我的示例中,该基类保存对象的名称。节点包含叶或节点的数组,由名为addChild()
的方法填充
实现与此类似:
<?php
abstract class Base
{
public $name;
public $previewImage; //path to preview image
public function __construct($name,$preview){
$this->name=$name;
$this->previewImage=$preview;
}
}
class SubGroup extends Base{
public $children= array();
public function getChildrenByPath(Array $subGroupPath){
//example: array("cat_1","cat_1-1",...);
$subChildren=$this->children;
foreach($subGroupPath as $currentPathStep){//follow subGroupPath
foreach($subChildren as $currentChildr){// step through children and compare to path
if($currentChild->uriPattern == $currentPathStep){
$subChildren=$currentChild->getChildren();
break; //end foreach
}
}
}
return $subChildren;
}
public function addChild(Base $new_child){
$this->children[]=$new_child;
}
public function getChildren(){
return $this->children;
}
}
class ProductType01 extends Base{
public property1,property2,property3;
}
?>
因此addChild()方法将项添加到第一个类别的数组中
演示
您可以在基类中添加父变量,并在addChild中设置它。检查null是必要的,但它允许您在树层次结构中双向移动。您可以在基类中添加父变量,并在addChild中设置它。检查null是必要的,但它允许您在树层次结构中双向移动。我不知道哪种设计模式是实现所需灵活性和易于实现结构的最佳方法代码>设计模式解决特定问题。你的问题陈述太笼统了。谢谢。嗯,我的意思是:我陈述了我的具体问题,并提出了一个可能的(开始的)解决方案,但如果可以做得更好,我希望有经验的人给我一些建议,或者可能会出现什么错误,或者在设置大的之后可能会遇到什么。我不知道哪种设计模式是实现所需的灵活性和易于实现的结构的最佳方法代码>设计模式解决特定问题。你的问题陈述太笼统了。谢谢。嗯,我的意思是:我陈述了我的具体问题并提出了一个可能的解决方案,但我希望有经验的人能给我一些建议,如果可以做得更好的话,或者可能会犯什么错误,或者在设置了大问题后我可能会遇到什么。
$cat01 = new SubGroup("category 01","preview_cat_01.png");
$cat01->addChild( new ProductType01("Item-01","preview_01.png"));
$cat01->addChild( new ProductType01("Item-02","preview_02.png"));
...
$products = new subGroup("","","products"); //very first node
$products->addChild($cat01);
<main>
<?php
$children=$products->getChildrenByPath($uri);
foreach($children as $value){
echo "<div class='previewImage_element'>";
echo "<img src='".$value->previewImage."' style='width:calc(120px *4/3);height:calc(120px*3/4);'>";
echo "<br /><a href='".."'>".$value->name."</a></div>\n";
}
?>
</main>