我会将其视为行为,这意味着product
and上的一种方法category
。例如:
{{ $product->trail() }}
其中product
知道如何计算它自己的category
面包屑轨迹。
首先,对于类别,我们给出了一种计算其自身上游部分的方法。
$category = function(string $name, $parent = null) {
return new class($name, $parent) {
public $name;
public $parent;
public function __construct(string $name, $parent = null) {
$this->name = $name;
$this->parent = $parent;
}
public function breadcrumbs(array $trail = []) {
$trail[] = $this->name;
return $this->parent ? $this->parent->breadcrumbs($trail) : $trail;
}
};
};
然后从产品中,我们可以要求它用分隔符计算它,作为回报给我们线索。
$product = function(string $name, ...$categories) use($category) {
$categories = array_reduce(array_reverse($categories), function($set, $item) use($category) {
if (!$set) {
return $category($item);
}
return $category($item, $set);
});
return new class($name, $categories) {
public $name;
public $categories;
public function __construct(string $name, $categories) {
$this->name = $name;
$this->categories = $categories;
}
public function trail(string $separator = ' / '): string {
return implode($separator, $this->categories->breadcrumbs());
}
};
};
然后像这样使用它:
$book = $product('Harry Potter', 'books', 'hardback', 'young-adult');
$shoes = $product('Air Jordans', 'shoes', 'mens', 'sports', 'basketball');
$tapeMeasure = $product('Stanley 25', 'hardware', 'tools', 'measurement');
var_dump(
$book->trail(), // books / hardback / young-adult
$shoes->trail(), // shoes / mens / sports / basketball
$tapeMeasure->trail() // hardware / tools / measurement
);
https://3v4l.org/FNKZI
如果您正在寻找更复杂的东西,您可以$product->trail()
使用装饰器进行扩展。
public function linkSimilar(string $separator = ' / '): string {
return $this->trail($separator, function(string $name) {
return sprintf('<a href="/category/%s?similar-to=product/%s">%s</a>', $name, $this->sku, $name);
});
}
...
$product->linkSimilar(' > ')
提供:
<a href="/category/hardware?similar-to=product/U425263">hardware</a>
> <a href="/category/tools?similar-to=product/U425263">tools</a>
> <a href="/category/measurement?similar-to=product/U425263">measurement</a>
https://3v4l.org/22n15