有效地主题化长字符串动态html


Effectively Theming long stringed dynamic html

我正在制作几个始终遵循已定义模板的HTML弹出窗口。

由于存在模板(标题、内容、示例表、更多按钮),我想我可以通过将数据传递给包装器函数来保存很多重复出现的html,比如:

$device_popup_data = array(
    'header' => 'Header text',
    'content' => 'some text<span style ="bold"> Some more text</span>',
    'example' => '<table><tbody><tr><td> A lot of text here, multi lined and messy',
    'more' => '',
);
echo theme_uxt_expanded_popup($device_popup_data);
function theme_uxt_expanded_popup($data){
    $head = isset($data['head'])?$data['head']:'';
    $content = isset($data['content'])?$data['content']:'';
    $example = isset($data['example'])?$data['example']:'';
    $more_html = isset($data['more'])?$data['more']:'';
    $output= '<div class = "expandedTooltip">';
    $output.=   '<h1>'.$head.'</h1>';
    $output.=   '<p>'.$content.'</p>';
    if(!empty($more)){
        $output.=   '<a class = "popupShowMore"><p>'.$more.'</p></a>';
    }
    $output .= '</div>';
    return $output;
}

这似乎是个好主意,直到我看到其中一些字段,如example字段,可能包含大约100行HTML。

将这些长字符串放入示例变量中似乎会使代码变得非常不可读。类似这样的东西:

$device_popup_data = array(
    'header' => 'Header text',
    'content' => 'some text<span style ="bold"> Some more text</span>',
    'example' => '<table><tbody><tr><td> A lot of text here</td>,<td> multi lined and 
    messy, and if any one</td>
 <td>wants to change this string it will be very hard</td> 
Real string is much longer ... </table>',
    'more' => '',
);

你知道有一种高效且可读的方法来做这样的事情吗?

你知道有什么有效且可读的方法可以做这样的事情吗这

做到这一点的唯一可读、可维护的方法是遵守关注点分离。这里的要点是1)将HTML与PHP解耦2)实现容器,如name=>HTML content

为了充分利用DISRP,您应该将其封装到一个类中(见下文)。因此,类本身看起来像:

class TemplateBlockManager
{
     private $blocks = array(); 
     public function define($name, $file, array $vars = array())
     {
          ob_start();
          if (!empty($vars)) {
              extract($vars);
          }
          require($file);
          $content = ob_get_clean();
          $this->blocks[$name] = $content;
     }
     public function getBlock($name)
     {
         return $this->blocks[$name];
     }
}

文件:test.phtml

<p>
   <b>Welcome to <?php echo $foo; ?></b>
</p>

用法:

<?php
$blockManager = new TemplateBlockManager();
$blockManager->define('header', '/path/to/test.phtml', array('foo' => 'bar'));
// Should output "Welcome to bar"
echo $blockManager->getBlock('header');

这种方法有很多优点:

  • 您可以在bootstrap阶段准备几个块,这样您的块就可以共享浏览页面这减少了代码重复

  • 您可以将$blockManager的实例注入到生成输出的其他类中。这对unit-testing有好处,因为它遵守依赖注入

  • 您还遵守单一责任原则

  • 您完全将HTML与PHP解耦,因为您的模板包含基本的(或没有)PHP逻辑

  • 由于你的模板是完全解耦的,你不必担心它们是长的还是小的。您只需定义一条通往一个的路径

  • 最后,HTMLPHP code都易于维护