# 使用視圖(Using Views)
# 使用視圖(Using Views)
視圖代表了應用程序中的用戶界面. 視圖通常是在 HTML 文件里嵌入 PHP 代碼,這些代碼僅僅是用來展示數據。視圖的任務是當應用程序發生請求時,提供數據給 web 瀏覽器或者其他工具。
[*Phalcon\\Mvc\\View*](#) 和 [*Phalcon\\Mvc\\View\\Simple*](#)負責管理你的MVC應用程序的視圖(View)層。
### 集成視圖到控制器(Integrating Views with Controllers)
當某個控制器已經完成了它的周期,Phalcon自動將執行傳遞到視圖組件。視圖組件將在視圖文件夾中尋找一個文件夾名與最后一個控制器名相同,文件命名與最后一個動作相同的文件執行。例如,如果請求的URL *<http://127.0.0.1/blog/posts/show/301>*, Phalcon將如下所示的方式按解析URL:
Server Address127.0.0.1Phalcon DirectoryblogControllerpostsActionshowParameter301調度程序將尋找一個“PostsController”控制器及其“showAction”動作。對于這個示例的一個簡單的控制器文件:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
}
public function showAction($postId)
{
// Pass the $postId parameter to the view
$this->view->postId = $postId;
}
}
```
```
setVar允許我們創建視圖變量,這樣可以在視圖模板中使用它們。上面的示例演示了如何傳遞 $postId 參數到相應的視圖模板。
### 分層渲染(Hierarchical Rendering)
[*Phalcon\\Mvc\\View*](#) 支持文件的層次結構,在Phalcon中是默認的視圖渲染組件。這個層次結構允許通用的布局點(常用的視圖)和以控制器命名的文件夾中定義各自的視圖模板
該組件使用默認PHP本身作為模板引擎,因此視圖應該以.phtml作為拓展名。如果視圖目錄是 *app/views* ,視圖組件會自動找到這三個視圖文件。
你不需要實現上面提到的所有文件。在文件的層次結構中 [*Phalcon\\Mvc\\View*](#) 將簡單地移動到下一個視圖級別。如果這三個視圖文件被實現,他們將被按下面方式處理:
```
<pre class="calibre14">```
<!-- app/views/posts/show.phtml -->
<h3>This is show view!</h3>
<p>I have received the parameter <?php echo $postId; ?></p>
```
```
```
<pre class="calibre14">```
<!-- app/views/layouts/posts.phtml -->
<h2>This is the "posts" controller layout!</h2>
<?php echo $this->getContent(); ?>
```
```
```
<pre class="calibre14">```
<!-- app/views/index.phtml -->
<html>
<head>
<title>Example</title>
</head>
<body>
<h1>This is main layout!</h1>
<?php echo $this->getContent(); ?>
</body>
</html>
```
```
注意方法 *$this->getContent()* 被調用的這行。這種方法指示 [*Phalcon\\Mvc\\View*](#) 在這里注入前面視圖層次結構執行的內容。在上面的示例中,輸出將會是:

請求生成的HTML的將為:
```
<pre class="calibre14">```
<!-- app/views/index.phtml -->
<html>
<head>
<title>Example</title>
</head>
<body>
<h1>This is main layout!</h1>
<!-- app/views/layouts/posts.phtml -->
<h2>This is the "posts" controller layout!</h2>
<!-- app/views/posts/show.phtml -->
<h3>This is show view!</h3>
<p>I have received the parameter 101</p>
</body>
</html>
```
```
### 使用模版(Using Templates)
模板視圖可以用來分享共同的視圖代碼。他們作為控制器的布局,所以你需要放在布局目錄。
Templates can be rendered before the layout (using `$this->view->setTemplateBefore()`) or they can be rendered after the layout (using `this->view->setTemplateAfter()`). In the following example the template (layouts/common.phtml) is rendered after the main layout (layouts/posts.phtml):
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function initialize()
{
$this->view->setTemplateAfter('common');
}
public function lastAction()
{
$this->flash->notice("These are the latest posts");
}
}
```
```
```
<pre class="calibre14">```
<!-- app/views/index.phtml -->
<html>
<head>
<title>Blog's title</title>
</head>
<body>
<?php echo $this->getContent(); ?>
</body>
</html>
```
```
```
<pre class="calibre14">```
<!-- app/views/layouts/common.phtml -->
<ul class="menu">
<li><a href="/">Home</a></li>
<li><a href="/articles">Articles</a></li>
<li><a href="/contact">Contact us</a></li>
</ul>
<div class="content"><?php echo $this->getContent(); ?></div>
```
```
```
<pre class="calibre14">```
<!-- app/views/layouts/posts.phtml -->
<h1>Blog Title</h1>
<?php echo $this->getContent(); ?>
```
```
```
<pre class="calibre14">```
<!-- app/views/posts/last.phtml -->
<article>
<h2>This is a title</h2>
<p>This is the post content</p>
</article>
<article>
<h2>This is another title</h2>
<p>This is another post content</p>
</article>
```
```
最終的輸出如下:
```
<pre class="calibre14">```
<!-- app/views/index.phtml -->
<html>
<head>
<title>Blog's title</title>
</head>
<body>
<!-- app/views/layouts/common.phtml -->
<ul class="menu">
<li><a href="/">Home</a></li>
<li><a href="/articles">Articles</a></li>
<li><a href="/contact">Contact us</a></li>
</ul>
<div class="content">
<!-- app/views/layouts/posts.phtml -->
<h1>Blog Title</h1>
<!-- app/views/posts/last.phtml -->
<article>
<h2>This is a title</h2>
<p>This is the post content</p>
</article>
<article>
<h2>This is another title</h2>
<p>This is another post content</p>
</article>
</div>
</body>
</html>
```
```
If we had used `$this->view->setTemplateBefore('common')`, this would be the final output:
```
<pre class="calibre14">```
<!-- app/views/index.phtml -->
<html>
<head>
<title>Blog's title</title>
</head>
<body>
<!-- app/views/layouts/posts.phtml -->
<h1>Blog Title</h1>
<!-- app/views/layouts/common.phtml -->
<ul class="menu">
<li><a href="/">Home</a></li>
<li><a href="/articles">Articles</a></li>
<li><a href="/contact">Contact us</a></li>
</ul>
<div class="content">
<!-- app/views/posts/last.phtml -->
<article>
<h2>This is a title</h2>
<p>This is the post content</p>
</article>
<article>
<h2>This is another title</h2>
<p>This is another post content</p>
</article>
</div>
</body>
</html>
```
```
### 渲染級別控制(Control Rendering Levels)
如上所述,[*Phalcon\\Mvc\\View*](#) 支持視圖分層。你可能需要控制視圖組件的渲染級別。方法 PhalconMvc\\View::setRenderLevel() 提供這個功能。
這種方法可以從控制器調用或是從上級視圖層干涉渲染過程。
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\View;
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
}
public function findAction()
{
// This is an Ajax response so it doesn't generate any kind of view
$this->view->setRenderLevel(View::LEVEL_NO_RENDER);
// ...
}
public function showAction($postId)
{
// Shows only the view related to the action
$this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
}
}
```
```
可用的渲染級別:
類常量解釋順 序LEVEL\_NO\_RENDER表明要避免產生任何形式的顯示。LEVEL\_ACTION\_VIEW生成顯示到視圖關聯的動作。1LEVEL\_BEFORE\_TEMPLATE生成顯示到控制器模板布局之前。2LEVEL\_LAYOUT生成顯示到控制器布局。3LEVEL\_AFTER\_TEMPLATE生成顯示到控制器模板布局后。4LEVEL\_MAIN\_LAYOUT生成顯示到主布局。文件: views/index.phtml5### 關閉渲染級別(Disabling render levels)
你可以永久或暫時禁用渲染級別。如果不在整個應用程序使用,可以永久禁用一個級別:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\View;
$di->set('view', function () {
$view = new View();
// Disable several levels
$view->disableLevel(
array(
View::LEVEL_LAYOUT => true,
View::LEVEL_MAIN_LAYOUT => true
)
);
return $view;
}, true);
```
```
或者在某些應用程序的一部分暫時或禁用:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\View;
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
}
public function findAction()
{
$this->view->disableLevel(View::LEVEL_MAIN_LAYOUT);
}
}
```
```
### 選擇視圖(Picking Views)
如上所述, 當 [*Phalcon\\Mvc\\View*](#) 由 [*Phalcon\\Mvc\\Application*](#) 視圖渲染的是最后的一個相關的控制器和執行動作。你可以使用 Phalcon\\Mvc\\View::pick() 方法覆蓋它。
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Controller;
class ProductsController extends Controller
{
public function listAction()
{
// Pick "views-dir/products/search" as view to render
$this->view->pick("products/search");
// Pick "views-dir/books/list" as view to render
$this->view->pick(array('books'));
// Pick "views-dir/products/search" as view to render
$this->view->pick(array(1 => 'search'));
}
}
```
```
### 關閉視圖(Disabling the view)
如果你的控制器不在視圖里產生(或沒有)任何輸出,你可以禁用視圖組件來避免不必要的處理:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Controller;
class UsersController extends Controller
{
public function closeSessionAction()
{
// Close session
// ...
// A HTTP Redirect
$this->response->redirect('index/index');
// Disable the view to avoid rendering
$this->view->disable();
}
}
```
```
你可以返回一個“response”的對象,避免手動禁用視圖:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Controller;
class UsersController extends Controller
{
public function closeSessionAction()
{
// Close session
// ...
// A HTTP Redirect
return $this->response->redirect('index/index');
}
}
```
```
### 簡單渲染(Simple Rendering)
[*Phalcon\\Mvc\\View\\Simple*](#) 是 `Phalcon\Mvc\View` 的大多數的設計思想,但缺少文件的層次結構是它們的主要區別。
該組件允許開發人員控制渲染視圖時,視圖所在位置。此外,該組件可以利用從視圖中繼承的可用的模板引擎。比如 [*Volt*](#) 和其他的一些模板引擎。
默認使用該的組件必須替換服務容器:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\View\Simple as SimpleView;
$di->set('view', function () {
$view = new SimpleView();
$view->setViewsDir('../app/views/');
return $view;
}, true);
```
```
自動渲染必須在 :doc:\[`](#)Phalcon\Mvc\Application <applications>`被禁用 (如果需要):
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Application;
try {
$application = new Application($di);
$application->useImplicitView(false);
echo $application->handle()->getContent();
} catch (\Exception $e) {
echo $e->getMessage();
}
```
```
渲染一個視圖必須顯式地調用render方法來指定你想顯示的視圖的相對路徑:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Controller;
class PostsController extends \Controller
{
public function indexAction()
{
// Render 'views-dir/index.phtml'
echo $this->view->render('index');
// Render 'views-dir/posts/show.phtml'
echo $this->view->render('posts/show');
// Render 'views-dir/index.phtml' passing variables
echo $this->view->render('index', array('posts' => Posts::find()));
// Render 'views-dir/posts/show.phtml' passing variables
echo $this->view->render('posts/show', array('posts' => Posts::find()));
}
}
```
```
### 使用局部模版(Using Partials)
局部模板是把渲染過程分解成更簡單、更好管理的、可以重用不同部分的應用程序塊的另一種方式。你可以移動渲染特定響應的代碼塊到自己的文件。
使用局部模板的一種方法是把它們作為相等的子例程:作為一種移動細節視圖,這樣您的代碼可以更容易地被理解。例如,您可能有一個視圖看起來像這樣:
```
<pre class="calibre14">```
<div class="top"><?php $this->partial("shared/ad_banner"); ?></div>
<div class="content">
<h1>Robots</h1>
<p>Check out our specials for robots:</p>
...
</div>
<div class="footer"><?php $this->partial("shared/footer"); ?></div>
```
```
方法 partial() 也接受一個只存在于局部范圍的變量/參數的數組作為第二個參數:
```
<pre class="calibre14">```
<?php $this->partial("shared/ad_banner", array('id' => $site->id, 'size' => 'big')); ?>
```
```
### 控制器傳值給視圖(Transfer values from the controller to views)
[*Phalcon\\Mvc\\View*](#) 可以在每個控制器中使用視圖變量 ($this->view)。 你可以在控制器動作中使用視圖對象的setVar()方法直接設置視圖變量。
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
}
public function showAction()
{
// Pass all the posts to the views
$this->view->setVar(
"posts",
Posts::find()
);
// Using the magic setter
$this->view->posts = Posts::find();
// Passing more than one variable at the same time
$this->view->setVars(
array(
'title' => $post->title,
'content' => $post->content
)
);
}
}
```
```
名為setVar()的第一參數值的變量將在視圖中創建的,并且可以被使用。變量可以是任何類型:從一個簡單的字符串,整數等等,變為更復雜的結構,如數組,集合。
```
<pre class="calibre14">```
<div class="post">
<?php
foreach ($posts as $post) {
echo "<h1>", $post->title, "</h1>";
}
?>
</div>
```
```
### 在視圖中使用模型(Using models in the view layer)
應用模型在視圖層也是可用的。[*Phalcon\\Loader*](#) 將在運行時實例化模型:
```
<pre class="calibre14">```
<div class="categories">
<?php
foreach (Categories::find("status = 1") as $category) {
echo "<span class='category'>", $category->name, "</span>";
}
?>
</div>
```
```
盡管你可以執行模型處理操作,如在視圖層 insert() 或 update(),但這是不推薦,因為在一個錯誤或異常發生時,它不可能將執行流程轉發給另一個控制器。
### 緩存視圖片段(Caching View Fragments)
有時當你開發動態網站和一些區域不會經常更新,請求的輸出是完全相同的。 [*Phalcon\\Mvc\\View*](#) 提供緩存全部或部分的渲染輸出來提高性能。
將 [*Phalcon\\Mvc\\View*](#) 配合 [*Phalcon\\Cache*](#) 能提供一種更簡單的方法緩存輸出片段。你可以手動設置緩存處理程序或一個全局處理程序。
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function showAction()
{
// Cache the view using the default settings
$this->view->cache(true);
}
public function showArticleAction()
{
// Cache this view for 1 hour
$this->view->cache(
array(
"lifetime" => 3600
)
);
}
public function resumeAction()
{
// Cache this view for 1 day with the key "resume-cache"
$this->view->cache(
array(
"lifetime" => 86400,
"key" => "resume-cache"
)
);
}
public function downloadAction()
{
// Passing a custom service
$this->view->cache(
array(
"service" => "myCache",
"lifetime" => 86400,
"key" => "resume-cache"
)
);
}
}
```
```
當我們沒有定義緩存的關鍵組件,這個組件會自動創建一個經過 [md5](http://php.net/manual/en/function.md5.php) 的當前渲染的視圖名。它是定義每個關鍵動作的一個良好實踐,這樣你可以很容易地識別與每個視圖關聯的緩存。
當視圖組件需要緩存的東西時,就會請求緩存服務的服務容器。這個服務的服務名稱約定為”viewCache”:
```
<pre class="calibre14">```
<?php
use Phalcon\Cache\Frontend\Output as OutputFrontend;
use Phalcon\Cache\Backend\Memcache as MemcacheBackend;
// Set the views cache service
$di->set('viewCache', function () {
// Cache data for one day by default
$frontCache = new OutputFrontend(
array(
"lifetime" => 86400
)
);
// Memcached connection settings
$cache = new MemcacheBackend(
$frontCache,
array(
"host" => "localhost",
"port" => "11211"
)
);
return $cache;
});
```
```
> 前端 Phalcon\\Cache\\Frontend\\Output 和服務 ‘viewCache' 必須在服務容器(DI)注冊為總是開放的(不共享 not shared)
在視圖中使用視圖緩存也是有用的,以防止控制器執行過程所產生的數據被顯示。
為了實現這一點,我們必須確定每個緩存鍵是獨一無二的。 首先,我們驗證緩存不存在或是否過期,再去計算/查詢并在視圖中顯示數據:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Controller;
class DownloadController extends Controller
{
public function indexAction()
{
// Check whether the cache with key "downloads" exists or has expired
if ($this->view->getCache()->exists('downloads')) {
// Query the latest downloads
$latest = Downloads::find(
array(
'order' => 'created_at DESC'
)
);
$this->view->latest = $latest;
}
// Enable the cache with the same key "downloads"
$this->view->cache(
array(
'key' => 'downloads'
)
);
}
}
```
```
[PHP alternative site](https://github.com/phalcon/php-site) 是實現緩存片段的一個例子。
### 模版引擎(Template Engines)
模板引擎可以幫助設計者不使用復雜的語法創建視圖。Phalcon包含一個強大的和快速的模板引擎,它被叫做叫 [*Volt*](#)。
此外, [*Phalcon\\Mvc\\View*](#) 允許你使用其它的模板引擎而不是簡單的PHP或者Volt。
使用不同的模板引擎,通常需要使用外部PHP庫并且引入復雜的文本解析來為用戶生成最終的輸出解析。這通常會增加一些你的應用程序的資源耗費。
如果一個外部模板引擎被使用,[*Phalcon\\Mvc\\View*](#) 提供完全相同的視圖渲染等級,仍然可以嘗試在這些模板內訪問的更多的API。
該組件使用的適配器,這些適配器幫助 Phalcon 與外部模板引擎以一個統一的方式對話,讓我們看看如何整合。
### 創建模版引擎(Creating your own Template Engine Adapter)
有很多模板引擎,你可能想整合或建立一個自己的。開始使用一個外部的模板引擎的第一步是創建一個適配器。
模板引擎的適配器是一個類,作為 [*Phalcon\\Mvc\\View*](#) 和模板引擎本身之間的橋梁。通常它只需要實現兩個方法: \_\_construct() and render()。首先接收 [*Phalcon\\Mvc\\View*](#) 和應用程序使用的DI容器來創建引擎適配器實例。
方法render()接受一個到視圖文件的絕對路徑和視圖參數,設置使用$this->view->setVar()。必要的時候,你可以讀入或引入它。
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Engine;
class MyTemplateAdapter extends Engine
{
/**
* Adapter constructor
*
* @param \Phalcon\Mvc\View $view
* @param \Phalcon\DI $di
*/
public function __construct($view, $di)
{
// Initialize here the adapter
parent::__construct($view, $di);
}
/**
* Renders a view using the template engine
*
* @param string $path
* @param array $params
*/
public function render($path, $params)
{
// Access view
$view = $this->_view;
// Access options
$options = $this->_options;
// Render the view
// ...
}
}
```
```
### 替換模版引擎(Changing the Template Engine)
你可以想下面一樣從控制器更換或者添加更多的模板引擎:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
// Set the engine
$this->view->registerEngines(
array(
".my-html" => "MyTemplateAdapter"
)
);
}
public function showAction()
{
// Using more than one template engine
$this->view->registerEngines(
array(
".my-html" => 'MyTemplateAdapter',
".phtml" => 'Phalcon\Mvc\View\Engine\Php'
)
);
}
}
```
```
你可以完全更換模板引擎或同時使用多個模板引擎。方法 Phalcon\\Mvc\\View::registerEngines() 接受一個包含定義模板引擎數據的數組。每個引擎的鍵名是一個區別于其他引擎的拓展名。模板文件和特定的引擎關聯必須有這些擴展名。
Phalcon\\Mvc\\View::registerEngines() 會按照相關順序定義模板引擎執行。如果 [*Phalcon\\Mvc\\View*](#) 發現具有相同名稱但不同的擴展,它只會使第一個。
如果你想在應用程序的每個請求中注冊一個或一組模板引擎。你可以在創建視圖時注冊服務:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\View;
// Setting up the view component
$di->set('view', function () {
$view = new View();
// A trailing directory separator is required
$view->setViewsDir('../app/views/');
$view->registerEngines(
array(
".my-html" => 'MyTemplateAdapter'
)
);
return $view;
}, true);
```
```
在 [Phalcon Incubator](https://github.com/phalcon/incubator/tree/master/Library/Phalcon/Mvc/View/Engine) 有一些適配器可用于數個模板引擎
### 注入服務到視圖(Injecting services in View)
每個視圖執行內部包含一個 [*Phalcon\\DI\\Injectable*](#) 實例, 提供方便地方式訪問應用程序的服務容器。
下面的示例演示如何用一個框架約定好的URL服務寫一個 jQuery [ajax request](http://api.jquery.com/jQuery.ajax/) 。“url” (usually [*Phalcon\\Mvc\\Url*](#)) 服務被注入在視圖由相同名稱的屬性訪問:
```
<pre class="calibre14">```
<script type="text/javascript">
$.ajax({
url: "<?php echo $this->url->get("cities/get"); ?>"
})
.done(function () {
alert("Done!");
});
</script>
```
```
### 獨立的組件(Stand-Alone Component)
在Phalcon的所有部件都可以作為膠水(*glue*) 組件單獨使用,因為它們彼此松散耦合:
### 分層渲染(Hierarchical Rendering)
如下所示,可以單獨使用 [*Phalcon\\Mvc\\View*](#):
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\View;
$view = new View();
// A trailing directory separator is required
$view->setViewsDir("../app/views/");
// Passing variables to the views, these will be created as local variables
$view->setVar("someProducts", $products);
$view->setVar("someFeatureEnabled", true);
// Start the output buffering
$view->start();
// Render all the view hierarchy related to the view products/list.phtml
$view->render("products", "list");
// Finish the output buffering
$view->finish();
echo $view->getContent();
```
```
使用短的語法也可以:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\View;
$view = new View();
echo $view->getRender('products', 'list',
array(
"someProducts" => $products,
"someFeatureEnabled" => true
),
function ($view) {
// Set any extra options here
$view->setViewsDir("../app/views/");
$view->setRenderLevel(View::LEVEL_LAYOUT);
}
);
```
```
### 簡單渲染(Simple Rendering)
如下所示,以單獨使用 [*Phalcon\\Mvc\\View\\Simple*](#):
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\View\Simple as SimpleView;
$view = new SimpleView();
// A trailing directory separator is required
$view->setViewsDir("../app/views/");
// Render a view and return its contents as a string
echo $view->render("templates/welcomeMail");
// Render a view passing parameters
echo $view->render(
"templates/welcomeMail",
array(
'email' => $email,
'content' => $content
)
);
```
```
### 視圖事件(View Events)
如果事件管理器(EventsManager)存在,[*Phalcon\\Mvc\\View*](#) 和 [*Phalcon\\Mvc\\View*](#) 能夠發送事件到 [*EventsManager*](#)。事件觸發使用的“view”類型。當返回布爾值false,一些事件可以停止運行。以下是被支持的事件:
事件名稱觸發點是否可以停止?beforeRender渲染過程開始前觸發YesbeforeRenderView渲染一個現有的視圖之前觸發YesafterRenderView渲染一個現有的視圖之后觸發NoafterRender渲染過程完成后觸發NonotFoundView視圖不存在時觸發No下面的例子演示了如何將監聽器附加到該組件:
```
<pre class="calibre14">```
<?php
use Phalcon\Mvc\View;
use Phalcon\Events\Manager as EventsManager;
$di->set('view', function () {
// Create an events manager
$eventsManager = new EventsManager();
// Attach a listener for type "view"
$eventsManager->attach("view", function ($event, $view) {
echo $event->getType(), ' - ', $view->getActiveRenderPath(), PHP_EOL;
});
$view = new View();
$view->setViewsDir("../app/views/");
// Bind the eventsManager to the view component
$view->setEventsManager($eventsManager);
return $view;
}, true);
```
```
下面的示例演示如何創建一個插件 [Tidy](http://www.php.net/manual/en/book.tidy.php) ,清理/修復的渲染過程中產生的HTML:
```
<pre class="calibre14">```
<?php
class TidyPlugin
{
public function afterRender($event, $view)
{
$tidyConfig = array(
'clean' => true,
'output-xhtml' => true,
'show-body-only' => true,
'wrap' => 0
);
$tidy = tidy_parse_string($view->getContent(), $tidyConfig, 'UTF8');
$tidy->cleanRepair();
$view->setContent((string) $tidy);
}
}
// Attach the plugin as a listener
$eventsManager->attach("view:afterRender", new TidyPlugin());
```
```
|
- [索引](# "總目錄")
- [下一頁](# "視圖助手(View Helpers)") |
- [上一頁](# "對象文檔映射 ODM (Object-Document Mapper)") |
- API參考
- API列表
- Abstract class Phalcon\Acl
- Abstract class Phalcon\Acl\Adapter
- Class Phalcon\Acl\Adapter\Memory
- Interface Phalcon\Acl\AdapterInterface
- Class Phalcon\Acl\Exception
- Class Phalcon\Acl\Resource
- Interface Phalcon\Acl\ResourceInterface
- Class Phalcon\Acl\Role
- Interface Phalcon\Acl\RoleInterface
- Class Phalcon\Annotations\Annotation
- Abstract class Phalcon\Annotations\Adapter
- Interface Phalcon\Annotations\AdapterInterface
- Class Phalcon\Annotations\Collection
- Class Phalcon\Annotations\Exception
- Class Phalcon\Annotations\Reader
- Interface Phalcon\Annotations\ReaderInterface
- Class Phalcon\Annotations\Reflection
- Class Phalcon\Assets\Collection
- Class Phalcon\Assets\Exception
- Interface Phalcon\Assets\FilterInterface
- Class Phalcon\Assets\Filters\Cssmin
- Class Phalcon\Assets\Filters\Jsmin
- Class Phalcon\Assets\Filters\None
- Class Phalcon\Assets\Inline
- Class Phalcon\Assets\Inline\Css
- Class Phalcon\Assets\Inline\Js
- Class Phalcon\Assets\Manager
- Class Phalcon\Assets\Resource
- Class Phalcon\Assets\Resource\Css
- Class Phalcon\Assets\Resource\Js
- Abstract class Phalcon\Cache\Backend
- Class Phalcon\Cache\Backend\Apc
- Class Phalcon\Cache\Backend\File
- Class Phalcon\Cache\Backend\Libmemcached
- Class Phalcon\Cache\Backend\Memcache
- Class Phalcon\Cache\Backend\Memory
- Class Phalcon\Cache\Backend\Mongo
- Class Phalcon\Cache\Backend\Redis
- Class Phalcon\Cache\Backend\Xcache
- Interface Phalcon\Cache\BackendInterface
- Class Phalcon\Cache\Exception
- Class Phalcon\Cache\Frontend\Base64
- Class Phalcon\Cache\Frontend\Data
- Class Phalcon\Cache\Frontend\Igbinary
- Class Phalcon\Cache\Frontend\Json
- Class Phalcon\Cache\Frontend\None
- Class Phalcon\Cache\Frontend\Output
- Interface Phalcon\Cache\FrontendInterface
- Class Phalcon\Cache\Multiple
- Class Phalcon\Cli\Router\Route
- Class Phalcon\Config
- Class Phalcon\Config\Adapter\Ini
- Class Phalcon\Config\Adapter\Json
- Class Phalcon\Config\Adapter\Php
- Class Phalcon\Config\Adapter\Yaml
- Class Phalcon\Config\Exception
- Class Phalcon\Crypt
- Class Phalcon\Crypt\Exception
- Interface Phalcon\CryptInterface
- Abstract class Phalcon\Db
- Abstract class Phalcon\Db\Adapter
- Interface Phalcon\Db\AdapterInterface
- Class Phalcon\Db\Column
- Interface Phalcon\Db\ColumnInterface
- Abstract class Phalcon\Db\Dialect
- Interface Phalcon\Db\DialectInterface
- Class Phalcon\Db\Exception
- Class Phalcon\Db\Index
- Interface Phalcon\Db\IndexInterface
- Class Phalcon\Db\Profiler
- Class Phalcon\Db\RawValue
- Class Phalcon\Db\Reference
- Interface Phalcon\Db\ReferenceInterface
- Class Phalcon\Db\Result\Pdo
- Interface Phalcon\Db\ResultInterface
- Class Phalcon\Debug
- Class Phalcon\Debug\Dump
- Class Phalcon\Debug\Exception
- Interface Phalcon\DiInterface
- Abstract class Phalcon\Dispatcher
- Interface Phalcon\DispatcherInterface
- Class Phalcon\Escaper
- Class Phalcon\Escaper\Exception
- Interface Phalcon\EscaperInterface
- Class Phalcon\Events\Event
- Interface Phalcon\Events\EventsAwareInterface
- Class Phalcon\Events\Exception
- Class Phalcon\Events\Manager
- Interface Phalcon\Events\ManagerInterface
- Class Phalcon\Exception
- Class Phalcon\Filter
- Class Phalcon\Filter\Exception
- Interface Phalcon\Filter\UserFilterInterface
- Interface Phalcon\FilterInterface
- Abstract class Phalcon\Flash
- Class Phalcon\Flash\Direct
- Class Phalcon\Flash\Exception
- Class Phalcon\Flash\Session
- Interface Phalcon\FlashInterface
- Class Phalcon\Forms\Form
- Abstract class Phalcon\Forms\Element
- Class Phalcon\Forms\Exception
- Class Phalcon\Forms\Manager
- Class Phalcon\Http\Cookie
- Class Phalcon\Http\Cookie\Exception
- Class Phalcon\Http\Request
- Class Phalcon\Http\Request\Exception
- Class Phalcon\Http\Request\File
- Interface Phalcon\Http\Request\FileInterface
- Interface Phalcon\Http\RequestInterface
- Class Phalcon\Http\Response
- Class Phalcon\Http\Response\Cookies
- Interface Phalcon\Http\Response\CookiesInterface
- Class Phalcon\Http\Response\Exception
- Class Phalcon\Http\Response\Headers
- Interface Phalcon\Http\Response\HeadersInterface
- Interface Phalcon\Http\ResponseInterface
- Class Phalcon\Image
- Abstract class Phalcon\Image\Adapter
- Class Phalcon\Image\Adapter\Imagick
- Interface Phalcon\Image\AdapterInterface
- Class Phalcon\Image\Exception
- Class Phalcon\Kernel
- Class Phalcon\Loader
- Class Phalcon\Loader\Exception
- Abstract class Phalcon\Logger
- Abstract class Phalcon\Logger\Adapter
- Class Phalcon\Logger\Adapter\File
- Class Phalcon\Logger\Adapter\Firephp
- Class Phalcon\Logger\Adapter\Stream
- Class Phalcon\Logger\Adapter\Syslog
- Interface Phalcon\Logger\AdapterInterface
- Class Phalcon\Logger\Exception
- Abstract class Phalcon\Logger\Formatter
- Interface Phalcon\Logger\FormatterInterface
- Class Phalcon\Logger\Item
- Class Phalcon\Logger\Multiple
- Class Phalcon\Mvc\Application
- Class Phalcon\Mvc\Application\Exception
- Abstract class Phalcon\Mvc\Collection
- Abstract class Phalcon\Mvc\Collection\Behavior
- Class Phalcon\Mvc\Collection\Behavior\SoftDelete
- Class Phalcon\Mvc\Collection\Behavior\Timestampable
- Interface Phalcon\Mvc\Collection\BehaviorInterface
- Class Phalcon\Mvc\Collection\Document
- Class Phalcon\Mvc\Collection\Exception
- Class Phalcon\Mvc\Collection\Manager
- Interface Phalcon\Mvc\Collection\ManagerInterface
- Interface Phalcon\Mvc\CollectionInterface
- Abstract class Phalcon\Mvc\Controller
- Interface Phalcon\Mvc\ControllerInterface
- Class Phalcon\Mvc\Dispatcher
- Class Phalcon\Mvc\Dispatcher\Exception
- Interface Phalcon\Mvc\DispatcherInterface
- Interface Phalcon\Mvc\EntityInterface
- Class Phalcon\Mvc\Micro
- Class Phalcon\Mvc\Micro\Collection
- Interface Phalcon\Mvc\Micro\CollectionInterface
- Class Phalcon\Mvc\Micro\Exception
- Class Phalcon\Mvc\Micro\LazyLoader
- Interface Phalcon\Mvc\Micro\MiddlewareInterface
- Abstract class Phalcon\Mvc\Model
- Abstract class Phalcon\Mvc\Model\Behavior
- Class Phalcon\Mvc\Model\Criteria
- Interface Phalcon\Mvc\Model\CriteriaInterface
- Class Phalcon\Mvc\Model\Exception
- Class Phalcon\Mvc\Model\Manager
- Interface Phalcon\Mvc\Model\ManagerInterface
- Class Phalcon\Mvc\Model\Message
- Interface Phalcon\Mvc\Model\MessageInterface
- Abstract class Phalcon\Mvc\Model\MetaData
- Interface Phalcon\Mvc\Model\MetaDataInterface
- Class Phalcon\Mvc\Model\Query
- Interface Phalcon\Mvc\Model\QueryInterface
- Class Phalcon\Mvc\Model\Relation
- Interface Phalcon\Mvc\Model\RelationInterface
- Interface Phalcon\Mvc\Model\ResultInterface
- Abstract class Phalcon\Mvc\Model\Resultset
- Abstract class Phalcon\Mvc\Model\Validator
- Interface Phalcon\Mvc\Model\ResultsetInterface
- Class Phalcon\Mvc\Model\Row
- Class Phalcon\Mvc\Model\Transaction
- Interface Phalcon\Mvc\Model\TransactionInterface
- Class Phalcon\Mvc\Model\ValidationFailed
- Interface Phalcon\Mvc\ModelInterface
- Interface Phalcon\Mvc\ModuleDefinitionInterface
- Class Phalcon\Mvc\Router
- Class Phalcon\Mvc\Router\Annotations
- Class Phalcon\Mvc\Router\Exception
- Class Phalcon\Mvc\Router\Group
- Interface Phalcon\Mvc\Router\GroupInterface
- Class Phalcon\Mvc\Router\Route
- Interface Phalcon\Mvc\Router\RouteInterface
- Interface Phalcon\Mvc\RouterInterface
- Class Phalcon\Mvc\Url
- Class Phalcon\Mvc\Url\Exception
- Interface Phalcon\Mvc\UrlInterface
- Class Phalcon\Mvc\User\Component
- Class Phalcon\Mvc\User\Module
- Class Phalcon\Mvc\User\Plugin
- Class Phalcon\Mvc\View
- Abstract class Phalcon\Mvc\View\Engine
- Interface Phalcon\Mvc\View\EngineInterface
- Class Phalcon\Mvc\View\Exception
- Class Phalcon\Mvc\View\Simple
- Interface Phalcon\Mvc\ViewBaseInterface
- Interface Phalcon\Mvc\ViewInterface
- Abstract class Phalcon\Paginator\Adapter
- Class Phalcon\Paginator\Adapter\Model
- Class Phalcon\Paginator\Adapter\NativeArray
- Class Phalcon\Paginator\Adapter\QueryBuilder
- Interface Phalcon\Paginator\AdapterInterface
- Class Phalcon\Paginator\Exception
- Class Phalcon\Queue\Beanstalk
- Class Phalcon\Queue\Beanstalk\Job
- Final class Phalcon\Registry
- Class Phalcon\Security
- Class Phalcon\Security\Exception
- Abstract class Phalcon\Session
- Abstract class Phalcon\Session\Adapter
- Interface Phalcon\Session\AdapterInterface
- Class Phalcon\Session\Bag
- Interface Phalcon\Session\BagInterface
- Class Phalcon\Session\Exception
- Class Phalcon\Tag
- Class Phalcon\Tag\Exception
- Abstract class Phalcon\Tag\Select
- Abstract class Phalcon\Text
- Abstract class Phalcon\Translate
- Abstract class Phalcon\Translate\Adapter
- Class Phalcon\Translate\Adapter\Csv
- Class Phalcon\Translate\Adapter\Gettext
- Class Phalcon\Translate\Adapter\NativeArray
- Interface Phalcon\Translate\AdapterInterface
- Class Phalcon\Translate\Exception
- Class Phalcon\Validation
- Class Phalcon\Validation\Exception
- Class Phalcon\Validation\Message
- Class Phalcon\Validation\Message\Group
- Interface Phalcon\Validation\MessageInterface
- Abstract class Phalcon\Validation\Validator
- Class Phalcon\Validation\Validator\Alnum
- Class Phalcon\Validation\Validator\Alpha
- Class Phalcon\Validation\Validator\Between
- Class Phalcon\Validation\Validator\Confirmation
- Class Phalcon\Validation\Validator\Digit
- Class Phalcon\Validation\Validator\Email
- Class Phalcon\Validation\Validator\ExclusionIn
- Class Phalcon\Validation\Validator\File
- Class Phalcon\Validation\Validator\Identical
- Class Phalcon\Validation\Validator\InclusionIn
- Class Phalcon\Validation\Validator\Numericality
- Class Phalcon\Validation\Validator\PresenceOf
- Class Phalcon\Validation\Validator\Regex
- Class Phalcon\Validation\Validator\StringLength
- Class Phalcon\Validation\Validator\Uniqueness
- Class Phalcon\Validation\Validator\Url
- Interface Phalcon\Validation\ValidatorInterface
- Class Phalcon\Version
- 參考手冊
- 安裝(Installation)
- 教程 1:讓我們通過例子來學習(Tutorial 1: Let’s learn by example)
- 教程 2:Introducing INVO(Tutorial 2: Introducing INVO)
- 教程 3: Securing INVO
- 教程 4: Using CRUDs
- 教程 5: Customizing INVO
- 教程 6: Vkuró
- 教程 7:創建簡單的 REST API(Tutorial 7: Creating a Simple REST API)
- 示例列表(List of examples)
- 依賴注入與服務定位器(Dependency Injection/Service Location)
- MVC 架構(The MVC Architecture)
- 使用控制器(Using Controllers)
- 使用模型(Working with Models)
- 模型元數據(Models Meta-Data)
- 事務管理(Model Transactions)
- Phalcon 查詢語言(Phalcon Query Language (PHQL))
- 緩存對象關系映射(Caching in the ORM)
- 對象文檔映射 ODM (Object-Document Mapper)
- 使用視圖(Using Views)
- 視圖助手(View Helpers)
- 資源文件管理(Assets Management)
- Volt 模版引擎(Volt: Template Engine)
- MVC 應用(MVC Applications)
- 路由(Routing)
- 調度控制器(Dispatching Controllers)
- 微應用(Micro Applications)
- 使用命名空間(Working with Namespaces)
- 事件管理器(Events Manager)
- Request Environment
- 返回響應(Returning Responses)
- Cookie 管理(Cookies Management)
- 生成 URL 和 路徑(Generating URLs and Paths)
- 閃存消息(Flashing Messages)
- 使用 Session 存儲數據(Storing data in Session)
- 過濾與清理(Filtering and Sanitizing)
- 上下文編碼(Contextual Escaping)
- 驗證(Validation)
- 表單(Forms)
- 讀取配置(Reading Configurations)
- 分頁(Pagination)
- 使用緩存提高性能(Improving Performance with Cache)
- 安全(Security)
- Encryption/Decryption
- 訪問控制列表 ACL(Access Control Lists ACL)
- 多語言支持(Multi-lingual Support)
- Universal Class Loader
- 日志記錄(Logging)
- 注釋解析器(Annotations Parser)
- 命令行應用(Command Line Applications)
- 隊列(Queueing)
- 數據庫抽象層(Database Abstraction Layer)
- 國際化(Internationalization)
- 數據庫遷移(Database Migrations)
- 調試應用程序(Debugging Applications)
- Phalcon 開發工具(Phalcon Developer Tools)
- 提高性能:下一步該做什么?(Increasing Performance: What’s next?)
- 單元測試(Unit testing)
- 授權(License)