表现控件
表现控件是什么?
A Presenter is a class that contains the logic that is needed to generate your view (or views). When the controller is done with your user input and is done with whatever actions it needed to take, it turns execution over to the Presenter to retrieve and process whatever data is needed for the view. A Presenter shouldn't do any data manipulation but can contain database calls and any other retrieval or preparation operations needed to generate the View's data.
表现控件是選擇性的,如果你不需要它們,你可以直接使用 Views,并保持在控制器中預处理邏輯。
建立一个表现控件
首先我們在 APPPATH/classes/presenter/index.php
建立一个空的 Presenter 类別:
class Presenter_Index extends Presenter
{
}
Then you create the view that is associated with the presenter in app/views/index.php
:
<h1><?php echo $title; ?></h1>
<ul>
<?php
foreach ($articles as $a)
{
echo '<li>'.$a->title.'</li>';
}
?>
</ul>
關於檢視名稱
A Presenter and its view are by default expected to share the same name. Thus a
Presenter Presenter_Index
expects the view to be in app/views/index.php
. And underscores
work here the same as with classes, which means that the view for Presenter_Some_Thing
is expected
to be in app/views/some/thing.php
.
This default can be overwritten by setting a non-static $_view
property in your Presenter with the
View name (without it's suffix), or passing a custom View name when forging the Presenter.
And last we'll create the Presenter from the controller:
$presenter = Presenter::forge('index');
Now we have everything setup; however, there is still no data passed to the view. It still needs to get a
$title
string and $articles
array passed to it. We do this by adding a view()
method
to the Presenter which will assign this data:
class Presenter_Index extends Presenter
{
public function view()
{
$this->title = 'Testing this Presenter thing';
$this->articles = Model_Articles::find('all');
}
}
你就大功告成了。
In your code, Views and Presenters are interchangeable. You can return Presenters from your controller actions, you can set a Presenter as a Theme partial, or assign it to a section of your page template. The basic API of the Presenter is compatible with the View. This makes it easy to swap a View for a Presenter in your code without having to do a major code overhaul.
傳遞函式到檢視
To pass a View specific function from your Presenter to your View, you use Closures:
// 在 Presenter 中
class Presenter_Index extends Presenter
{
public function view()
{
$this->echo_upper = function($string) { echo strtoupper($string); };
}
}
// 然後你可以在你的檢視使用:
$echo_upper('this string'); // 輸出:"THIS STRING"