jamierumbelow / presenters
使用 PHP presenters 清理您的视图
1.0.0
2012-12-04 11:00 UTC
Requires
- php: >=5.3.2
Requires (Dev)
- phpunit/phpunit: 3.7.*
This package is not auto-updated.
Last update: 2024-09-14 15:06:05 UTC
README
很容易就会编写出复杂、脆弱的视图,其中充满了混乱的逻辑和展示代码,这些代码实际上应该在别处。在我的书中,《CodeIgniter 手册 - 第一卷 - 谁需要 Ruby?》中,我讨论了一种清理视图的出色技术。
这个小型库是一个轻量级、经过测试的解决方案,用于在 PHP(和 CodeIgniter 应用程序)中使用 presenters。**这个库针对 CI 量身定制,但可以与任何 PHP 应用程序一起工作。**
概述
class Book_Presenter extends Presenter
{
public function price()
{
return number_format($this->book->price, 2);
}
}
$book = $this->db->where('id', 1)->get('books')->row();
$book = new Book_Presenter($book);
echo $book->title() . ' costs ' . $book->price();
安装
将其添加到您的 composer.json
{
"require": {
"jamierumbelow/presenters": "*"
}
}
运行 composer update
$ php composer.phar update
...并自动加载
require_once 'vendor/autoload.php';
使用方法
创建一个以 _Presenter
为后缀的新类。 Book_presenter
将创建一个 $this->book
变量,Game_Type_Presenter
将创建一个 $this->game_type
变量。
实例化一个新的 presenter 对象,并通过原始对象传递
$book = $this->db->where('id', 1)->get('books')->row();
$book = new Book_Presenter($book);
然后您可以访问 presenter 内部的数据
class Book_Presenter extends Presenter
{
public function title()
{
return $this->book->title . ' - ' . $this->book->subtitle;
}
}
如果您想自定义对象名称,将其作为第二个参数传递
$book = new Book_Presenter($book, 'bookObject');
class Book_Presenter extends Presenter
{
public function title()
{
return $this->bookObject->title . ' - ' . $this->bookObject->subtitle;
}
}