开放的编程资料库

当前位置:我爱分享网 > PHP教程 > 正文

File_Fortune 重构

在过去的几个晚上,我重构了File_Fortune以让它实现IteratorCountableArrayAccess—基本上允许它像一个大多数意图和目的的数组。因此,我消除了对File_Fortune_Writer包的需求,并大大简化了使用。

(注意:当然,File_Fortune可能没什么大不了的,但在过去两年中超过1000次的下载表明有人正在使用它。另外,它为家庭网站上的随机引述。:-))

举几个例子:

require_once 'File/Fortune.php';

// Initialize and point it to a directory of fortunes
$fortunes = new File_Fortune('/path/to/fortunedir');

// Retrieve a random fortune 
// (works with either a directory or a single fortune file)
echo $fortunes->getRandom();

// Set to a specific fortune file:
$fortunes->setFile('myfortunes');

// Loop through and print all fortunes
foreach ($fortunes as $fortune) {
    echo str_repeat('-', 72), "\n", $fortune, "\n\n";
}

// Hmmm.. let's change one:
$fortunes[7] = "I never really liked that fortune anyways.";

// No need to explicitly save, as it's done during __destruct(), 
// but if you really want to:
$fortunes->save();

// Let's add a new fortune:
$fortunes->add('This is a shiny new fortune!');

// and now we'll verify it exists:
$index = count($fortunes) - 1;
echo $fortunes[$index];

总而言之,这是一个更好的界面。经验教训:从其他语言移植代码时,花些时间确定您自己的API是否更好是值得的。

在即将发布的版本中,我希望修改后端以使用PHP的StreamsAPI而不是直接文件访问,并且还允许明确提供一个fortunefiles列表。之后,我应该为初始稳定版本做好准备。

更新(2007-07-10):修复了示例中的解析错误

未经允许不得转载:我爱分享网 » File_Fortune 重构

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏