// This class has 3 properties defining 3 differend markup elements.
// I need to be able to change the output of $x, $y and $z easilly.
class XYZ {
protected static $x = \'<div class="something_wrap">%s</div>\';
protected static $y = \'<div class="something_inner">%s</div>\';
protected static $z = \'<div class="something_inner">%s</div>\';
}
SHORT VERSION:
我正在开发的插件必须在输出中高度可定制。我可以用WordPress\'
filters 或者定义一些
setters.我想知道哪种方法是最好的,为什么。
LONG VERSION:
我想在不同网站的插件中使用这个类。在每个标签上,标记将略有不同(以适应布局/间距差异),因此必须易于自定义。一个解决方案是使用
static setters 用于定义标记。例如:
// I can define a "global/site-wide" markup with just three lines in my functions.php.
// I could then hook those three lines in a wp_head hook, just to make sure they won\'t run more than once.
XYZ::setStaticX( \'<div class="something_wrap row col-12 p-5">%s</div>\' );
XYZ::setStaticY( \'<div class="something_inner col-12 col-sm-6">%s</div>\' );
XYZ::setStaticZ( \'<div class="something_inner col-12 col-sm-6">%s</div>\' );
// If I ever require a different "X" markup for a specific instance of the class, I can do this:
$example = new XYZ;
$example->setX( \'%s\' );
另一种选择是使用Wordpress\'
filters:
// Again, I can define a "global/site-wide" behaviour like this:
add_filter( \'xyz_filter_x\', function( $value ) {
return \'<div class="something_wrap row col-12 p-5">%s</div>\';
}, 10 );
add_filter( \'xyz_filter_y\', function( $value ) {
return \'<div class="something_inner col-12 col-sm-6">%s</div>\';
}, 10 );
add_filter( \'xyz_filter_z\', function( $value ) {
return \'<div class="something_inner col-12 col-sm-6">%s</div>\';
}, 10 );
// And then if I need to customize something, I could change the first filter to be something like this:
add_filter( \'xyz_filter_x\', function( $value, $id ) {
if ( $id === 5 ) {
return \'%s\';
} else {
return \'<div class="something_wrap row col-12 p-5">%s</div>\';
}
}, 10, 2 );
我相信第二种方法符合WordPress的指导原则,但一旦在
functions.php
. 另一方面,第一种方法对我来说似乎更具可读性和清晰性,但我想知道这个特定的解决方案是否有任何缺点。
这让我想知道哪种方法是最好的,为什么。