PHP开发必备 一步步学PHP模版引擎Dwoo(1)
PHP目前是使用最广泛的脚本解析动态语言之一。在PHP的开发当中,开发者都很关心的一个问题是,如何最大程度地将页面和商业逻辑分离。而目前的很多PHP的开发框架,在这方面都有很好的解决方案,比如Zend,Agavi,CakePHP和CodeIgniter。然而,假如你的项目不是太大而没使用这些框架时,则可以选用一些开源的PHP模版引擎来实现页面和逻辑的分离,目前比较著名的有Smarty。本文将介绍另一款新兴的PHP模版引擎Dwoo,它同样有很多优点,值得读者去学习。
一、安装Dwoo
首先到Dwoo的官方网站下载()最新的版本1.1.7。在下载后,解压dwoo,将解压目录命名为dwoo,当然,你也可以用pear的安装方法安装,方法为: pear channel-discover pearhub.org
pear install pearhub/Dwoo
二、Dwoo模版简介
在Dwoo中,跟象Smarty等模版引擎差不多的是,它允许用户用普通的HTML编辑工具编辑表现层的页面,然后在需要产生动态内容的地方用占位符表示。模版引擎在解析的时候,会把如数据库中的或者业余逻辑计算结果填充到这些占位符中。下面先看一个简单的例子。 我们先建立一个模版文件,Dwoo的模版文件默认是tpl,当然你也可以改为其他文件后缀。模版文件名为knock.tpl,把它保存在template文件夹中,内容为: 1. <html>
2. <head></head>
3. <body>
4. <blockquote>
5. Knock knock! <br/>
6. Who's there? <br/>
7. {$name} <br/>
8. {$name} who? <br/>
9. {$punchline}
10. </blockquote>
11. </body>
12. </html>
可以看到,在Dwoo中,模版文件中,把需要动态更替的内容用{$ }这样的形式包裹起来,作为占位符,占位符当中的内容到时会被自动更替为实际的内容。接下来看如何使用Dwoo,代码如下: 13. <?php
14. include'dwooAutoload.php';
15. // 创建dwoo实例
16. $dwoo = newDwoo();
17. //读取模版文件
18. $tpl = newDwoo_Template_File('tmpl/knock.tpl');
19. // 对模版变量赋值
20. $data = array();
21. $data['name'] = 'Boo';
22. $data['punchline'] = 'Don\'t cry, it\'s only a joke';
23. // 将实际内容输出到模版
24. $dwoo->output($tpl, $data);
25. ?>
下面是使用Dwoo的几个步骤:
1、首先要包含Dwoo自动装载类dwooAutoload.php,这个类是自动加载了Dwoo模版所需要的其他依赖的类和工具类;
2、创建Dwoo类的实例;
3、通过new Dwoo_Template_File的方法加载模版,其中的参数为模版文件所在的路径;
4、设置要向模版文件中输出的替换内容,在Dwoo中,只需要通过定义一个关联数组的方法即可,数组中每个元素的名称跟模版文件中的占位符一一对应,数组中的每个值,就是要替换模版中的实际内容;
5、通过调用output方法,将数据向模版中输出,传入的参数为输出的数组内容和模版路径。
下图为输出结果:
? PHP开发必备 一步步学PHP模版引擎Dwoo(2)
三、Dwoo语法讲解
下面以实例的形式讲解下Dwoo的语法,先来看最常用的if语句。
1) if 语句
下面是一个模版的例子: 1. <html>
2. <head></head>
3. <body>
4. {if $auth == 0}
5. Not logged in
6.
{else}
7. Logged in as: Anonymous User
8. {/if}
9. </body>
10. </html>
可以看到,Dwoo中的if语句其实跟普通的if语句没什么区别。接下来我们看下控制这个模版的php文件,如下:
11. <?php
12. include'dwooAutoload.php';
13. try {
14. $dwoo = newDwoo();
15. $tpl = newDwoo_Template_File('tmpl/auth.tpl');
16. $data = newDwoo_Data();
17. $data->assign('auth', rand(0,1));
18. $dwoo->output($tpl, $data);
19. } catch (Exception $e) {
20. echo"Error: " . $e->getMessage();
21. }
22. ?>
注意,这里我们使用了new
Dwoo_Data();这个Dwoo_Data()方法的优势在于,它比较容易存放大量的数据,比用数组的方法去存储数据方便多了,而且它本身提供了很多不同的方法去获得,清理和删除模版变量。这个例子中,用随机数的方法产生了auth变量,结果可能为如下图:
当然,可以使用if elseif语句,比如模版中:
23. <html>
24. <head></head>
25. <body>
26. {if $auth == 1}
27. Logged in as: Anonymous User
28. {elseif $auth == 2}
29. Logged in as: Administrator
30. {else}
31. Not logged in
32. {/if}
33. </body>
34. </html>
2) LOOP循环语句
在Dwoo中,可以使用{loop}进行循环,动态产生数据,下面是例子: 35. <html>
36. <head></head>
37. <body>
38. <ul>
39. {loop $items}
40. <li>{escape($item)}</li>
41. {/loop}
42. </ul>
43. </body>
44. </html>
下面是产生数据的php文件: 45. <?php
46. include'dwooAutoload.php';
47. try {
48. $dwoo = newDwoo();
49. $tpl = newDwoo_Template_File('tmpl/list.tpl');
50. $data = newDwoo_Data();
51. $items = array();
52. $items[] = array('item' =>'red');
53. $items[] = array('item' =>'yellow');
54. $items[] = array('item' =>'blue');
55. $items[] = array('item' =>'green');
56. $data->assign('items', $items);
57. $dwoo->output($tpl, $data);
58. } catch (Exception $e) {
59. echo"Error: " . $e->getMessage();
60. }
61. ?>
这里,我们生成了数组items,然后在模版文件中,通过{loop $items}即可循环输出内容。结果如下图:
注意,这里使用了{escape($item)}的方法输出每一行的内容,其中eascape是dwoo中使用的插件,是将所有内容在输出前使用HTML编码格式过滤,这可以防止XSS攻击,是个很好的实践。
而在Dwoo中,可以同样使用{foreach}而达到同样的效果,代码如下: 62. <html>
63. <head></head>
64. <body>
65. <ul>
66. {foreach $items item}
67. <li>{escape($item)}</li>
68. {/foreach}
69. </ul>
70. </body>
71. </html> 同样,foreach也可以使用如下的用法,即:
72. <html>
73. <head></head>
74. <body>
75. <ul>
76. {foreach $items key value}
77. <li>{upper($key)} is for {$value}</li>
78. {/foreach}
79. </ul>
80. </body>
81. </html>
而配合这个模版,PHP的控制页面中的关联数组的写法如下: 82. $data = newDwoo_Data();
83. $items = array(
84. 'a' =>'apple',
85. 'b' =>'ball',
86. 'c' =>'cat',
87. 'd' =>'dog'
88. );
89. $data->assign('items', $items);
这样输出结果如下图:
我们既然学会了loop,下面来尝试下从数据库中取出数据集,并通过Dwoo显示出来,下面是模版文件的主要部分: 90. <body>
91.
<table>
92. <trclass="heading">
93. <td>Author</td>
94. <td>Title</td>
95. </tr>
96. {loop $records}
97. <tr>
98. <td>{$author}</td>
99. <td>{$title}</td>
100. </tr>
101. {/loop}
102. </table>
103. </body>
而PHP文件代码如下,其中使用了PDO去访问数据库: 104. <? php
105. include'dwooAutoload.php';
106. // 连接数据库
107. try {
108. $dbh = new PDO('mysql:dbname=library;host=localhost', 'user', 'pass'); 109. } catch (PDOException$e) {
110. echo"Error: Could not connect. " . $e->getMessage();
111. }
112. $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 113. try {
114. $sql = "SELECT a.AuthorName AS author, t.TitleName AS title FROM author
AS a, title AS t, author_title AS at WHERE a.AuthorID = at.AuthorID AND t.TitleID = at.TitleID ORDER BY author LIMIT 0,20";
115. $sth = $dbh->query($sql);
116. while ($row = $sth->fetchObject()) {
117. $records[] = array('author' =>$row->author, 'title' =>$row->title); 118. }
119. //关闭数据库连接
120. unset($dbh);
121. $dwoo = newDwoo();
122. $tpl = newDwoo_Template_File('tmpl/books.tpl');
123. $data = newDwoo_Data();
124. $data->assign('records', $records);
125. $dwoo->output($tpl, $data);
126. } catch (PDOException$e) {
127. echo"Error: Could not execute query \"$sql\". " . $e->getMessage(); 128. unset($dbh);
129. } catch (Exception $e) {
130. echo"Error: " . $e->getMessage();
131. }
132. ?>
? PHP开发必备 一步步学PHP模版引擎Dwoo(3)
四、模版组合
在页面设计中,常用的最佳实践是把一个复杂的页面划分为不同的部分,同样模版文件中也应该指定不同的部分,最后再将其组合起来,比如下图是常件的模版件结构:
可以看到有头部,尾部和页面的主体三部分组成,下面给出它们的模版文件header.tpl: 1. <!-- BEGIN header.tpl -->
2. <html>
3.
<head></head>
4. <body>
5. <tablewidth="100%"border="1">
6. <tr>
7. <tdalign="center"><ahref="#">Home</a></td>
8. <tdalign="center"><ahref="#">News</a></td>
9. <tdalign="center"><ahref="#">Weather</a></td>
10. <tdalign="center"><ahref="#">Hotels</a></td>
11. <tdalign="center"><ahref="#">Dining</a></td>
12. </tr>
13. </table>
14. <p/>
15. <h2>{$title}</h2>
16. <p/>
17. <!-- END header.tpl -->
18. footer.tpl
19. <!-- BEGIN footer -->
20. <tablewidth="100%"align="center">
21. <tr>
22. <tdalign="center"><fontsize="-2">© {$year}. All rights
reserved.</font></td>
23. </tr>
24. </table>
25. </body>
26. </html>
而Dwoo中,使用include可以将不同的模版包含到同一个模版中去,比如下面是框架主模版文件main.tpl: 27. {include(file='header.tpl')}
28. <!-- BEGIN main.tpl -->
29. <tableborder="1">
30. <tr>
31. <tdvalign="top">
32. <strong>{$headline}</strong>
33. <p/>
34. {$content}
35. </td>
36. <tdvalign="top"align="center"width="25%">
37. <strong>Special Feature</strong><br/>
38. {$feature}
39. </td>
40. </tr>
41. </table>
42. <!-- END main.tpl -->
43. {include(file='footer.tpl')}
而框架文件的php文件如下,可以为主框架模版中的变量赋值:
44. <?php
45. include'dwooAutoload.php';
46. try {
47. $dwoo = newDwoo();
48. $tpl = newDwoo_Template_File('tmpl/main.tpl');
49. $data = newDwoo_Data();
50. $data->assign('title', 'Welcome to London!');
51. $data->assign('headline', 'Playing in the Park');
52. $data->assign('content', 'It\'s a warm summer day, and Simon finds the lake
in St. James Park too inviting for words...');
53. $data->assign('feature', 'Tower Bridge - Snapshots from the Top');
54. $data->assign('year', date('Y', mktime()));
55. $dwoo->output($tpl, $data);
56. } catch (Exception $e) {
57.
echo"Error: " . $e->getMessage();
58. }
59. ?>
可以得出如下结果:
而另外的实现方法,是不使用include,而是在主框架模版中如下设置:
60. {$header}
61. <!-- BEGIN main.tpl -->
62. <tableborder="1">
63. <tr>
64. <tdvalign="top">
65. <strong>{$headline}</strong>
66. <p/>
67. {$content}
68. </td>
69. <tdvalign="top"align="center"width="25%">
70. <strong>Special Feature</strong><br/>
71. {$feature}
72. </td>
73. </tr>
74. </table>
75. <!-- END main.tpl -->
76. {$footer}
而在PHP文件中,再动态设置header和footer的变量的值,
77. $data->assign('header',$dwoo->get(newDwoo_Template_File('tmpl/header.t
pl'), $data));
78. $data->assign('footer',$dwoo->get(newDwoo_Template_File('tmpl/footer.t
pl'), $data));
这里使用了Dwoo中的get方法,将两个模版文件中的内容提取出来,设置到header和footer两个变量中去。
? PHP开发必备 一步步学PHP模版引擎Dwoo(4)
五、Dwoo中的插件机制
在Dwoo中,为开发者提供了大量方便的插件,比如前文提到的escape过滤功能,也是Dwoo 的插件之一。下面再学习一个同样功能的插件auto_esacpe,它其实实现的是跟escape一样的功能,但它可以针对一整段的模版变量进行格式化,比如,如下的模版:
1. <html>
2. <head></head>
3. <body>
4. {auto_escape on}
5. {$html}
6. {/auto_escape}
7. </body>
8. </html>
这里使用了{auto_escape on},表明在 {/auto_escape}前的输出全部要进行HTML格式化,考察如下的php脚本:
9. <?php
10. include'dwooAutoload.php';
11. try {
12. $dwoo = newDwoo();
13. $tpl = newDwoo_Template_File('tmpl/out.tpl');
14. $data = array();
15. $data['html']= '<span id="ack">Welcome to Jack & Jill\'s humble
abode.</span>';
16.
$dwoo->output($tpl, $data);
17. } catch (Exception $e) {
18. echo"Error: " . $e->getMessage();
19. }
20. ?>
其输出为如下图:
同样,Dwoo也有象php中的strip_tags方法,用来去掉HTML标记,比如:
21. <html>
22. <head></head>
23. <body>
24. {strip_tags($html)}
25. </body>
26. </html>
对应的PHP脚本为:
27. $data = array();
28. $data['html'] = '<a href="">Search</a>';
那么将会输出如下结果:
下面再介绍Dwoo中关于日期格式化的处理,其中可以使用date_format这个插件,这个插件需要传入两个参数,一个是要处理的日期,另外一个是指定用什么格式去格式化处理日期,举个例子: 29. <html>
30. <head></head>
31. <body>
32. {date_format $date "%d.%m.%Y"}
33. <br/>
34.
{date_format $date "%B %d, %Y %I:%M %p"}
35. </body>
36. </html>
处理的PHP代码的核心部分:
37. $data = array();
38. $data['date'] = '14 July 2010 21:35';
下面为其输出:
小结
在本文中,介绍了PHP模版引擎Dwoo的基本原理和用法,给读者一个快速的入门,在下一篇中,将深入介绍挖掘Dwoo中的一些特色功能。
【编辑推荐】
39. PHP开发必备 PHP持续集成工具介绍(上)
40. PHP开发必备 PHP持续集成工具介绍(下)
41. PHP正则表达式 PHP中的正则函数
42. PHP中几个常用的时间应用方式
【责任编辑:QiHappy TEL:(010)68476606】