三、编写自己的插件
Dwoo中的一个前大功能是能可以让开发者编写插件,并通过Dwoo的addplugin机制加载自己写的类,现举一个简单例子说明。比如下面的代码,封装了对email的操作:
- <?php
- function fix_address(Dwoo $dwoo, $str) {
- return str_replace(
- array('@', '.', '-'),
- array(' at ', ' dot ', ' dash '),
- $str
- );
- }
- include 'dwooAutoload.php';
- try {
- $dwoo = new Dwoo();
- $tpl = new Dwoo_Template_File('tmpl/plugin.tpl');
- $dwoo->addPlugin('email_safe', 'fix_address');
- $data['string']= 'vikram@example.com';
- $dwoo->output($tpl, $data);
- } catch (Exception $e) {
- echo "Error: " . $e->getMessage();
- }
- ?>
在这个例子中,我们想将用户EMAIL中的象@,分隔符等符号用英文替换掉,这样防止象网上机器人等去采集EMAIL,泄露私隐。其中fix_address方法为替换的方法。而通过dwoo中的addPlugin方法,命名一个插件,名字为email_safe,而插件的内容则指定为fix_address方法。在使用这个插件时,可以如下使用,plugin.tpl内容为:
- {email_safe($string)}
下图为输出结果:
而另外一种使用dwoo插件的方法为继承Dwoo_Filter abstract class,如下:
- <?php
- class Dwoo_Plugin_email_safe extends Dwoo_Plugin
- {
- public function process($email)
- {
- return str_replace(
- array('@', '.', '-'),
- array(' at ', ' dot ', ' dash '),
- );
- }
- }
- ?>
如果用这种方式的话,则可以把该文件保存在dwoo目录下的plugins目录下,则dwoo的自动加载机制会自动加载这个插件,而不用每次使用时都使用addplugin的功能。
PHP之友评论