文档
Welcome! 安装(Installation) 示例列表(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)
教程

发布于 2015-08-21 15:16:00 | 421 次阅读 | 评论: 0 | 来源: 网络整理

视图助手(View Helpers)

Writing and maintaining HTML markup can quickly become a tedious task because of the naming conventions and numerous attributes that have to be taken into consideration. Phalcon deals with this complexity by offering PhalconTag, which in turn offers view helpers to generate HTML markup.

This component can be used in a plain HTML+PHP view or in a Volt template.

This guide is not intended to be a complete documentation of available helpers and their arguments. Please visit the PhalconTag page in the API for a complete reference.

文档类型(Document Type of Content)

Phalcon provides PhalconTag::setDoctype() helper to set document type of the content. Document type setting may affect HTML output produced by other tag helpers. For example, if you set XHTML document type family, helpers that return or output HTML tags will produce self-closing tags to follow valid XHTML standard.

Available document type constants in PhalconTag namespace are:

Constant Document type
HTML32 HTML 3.2
HTML401_STRICT HTML 4.01 Strict
HTML401_TRANSITIONAL HTML 4.01 Transitional
HTML401_FRAMESET HTML 4.01 Frameset
HTML5 HTML 5
XHTML10_STRICT XHTML 1.0 Strict
XHTML10_TRANSITIONAL XHTML 1.0 Transitional
XHTML10_FRAMESET XHTML 1.0 Frameset
XHTML11 XHTML 1.1
XHTML20 XHTML 2.0
XHTML5 XHTML 5

Setting document type.

<?php

use PhalconTag;

$this->tag->setDoctype(Tag::HTML401_STRICT);

?>

Getting document type.

<?= $this->tag->getDoctype() ?>
<html>
<!-- your HTML code -->
</html>

The following HTML will be produced.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
<!-- your HTML code -->
</html>

Volt syntax:

{{ get_doctype() }}
<html>
<!-- your HTML code -->
</html>

创建表单(Creating Forms)

Forms in web applications play an essential part in retrieving user input. The following example shows how to implement a simple search form using view helpers:

<!-- Sending the form by method POST -->
<?= $this->tag->form("products/search") ?>
    <label for="q">Search:</label>
    <?= $this->tag->textField("q") ?>
    <?= $this->tag->submitButton("Search") ?>
<?= $this->tag->endForm() ?>

<!-- Specifying another method or attributes for the FORM tag -->
<?= $this->tag->form(array("products/search", "method" => "get")); ?>
    <label for="q">Search:</label>
    <?= $this->tag->textField("q"); ?>
    <?= $this->tag->submitButton("Search"); ?>
<?= $this->tag->endForm() ?>

This last code will generate the following HTML:

<form action="/store/products/search/" method="get">
     <label for="q">Search:</label>
     <input type="text" id="q" value="" name="q" />
     <input type="submit" value="Search" />
</form>

Same form generated in Volt:

<!-- Specifying another method or attributes for the FORM tag -->
{{ form("products/search", "method": "get") }}
    <label for="q">Search:</label>
    {{ text_field("q") }}
    {{ submit_button("Search") }}
{{ endForm() }}

Phalcon also provides a form builder to create forms in an object-oriented manner.

使用助手生成表单控件(Helpers to Generate Form Elements)

Phalcon provides a series of helpers to generate form elements such as text fields, buttons and more. The first parameter of each helper is always the name of the element to be generated. When the form is submitted, the name will be passed along with the form data. In a controller you can get these values using the same name by using the getPost() and getQuery() methods on the request object ($this->request).

<?php echo $this->tag->textField("username") ?>

<?php echo $this->tag->textArea(array(
    "comment",
    "This is the content of the text-area",
    "cols" => "6",
    "rows" => 20
)) ?>

<?php echo $this->tag->passwordField(array(
    "password",
    "size" => 30
)) ?>

<?php echo $this->tag->hiddenField(array(
    "parent_id",
    "value"=> "5"
)) ?>

Volt syntax:

{{ text_field("username") }}

{{ text_area("comment", "This is the content", "cols": "6", "rows": 20) }}

{{ password_field("password", "size": 30) }}

{{ hidden_field("parent_id", "value": "5") }}

使用选择框(Making Select Boxes)

Generating select boxes (select box) is easy, especially if the related data is stored in PHP associative arrays. The helpers for select elements are PhalconTag::select() and PhalconTag::selectStatic(). PhalconTag::select() has been was specifically designed to work with PhalconMvcModel, while PhalconTag::selectStatic() can with PHP arrays.

<?php

// Using data from a resultset
echo $this->tag->select(
    array(
        "productId",
        Products::find("type = 'vegetables'"),
        "using" => array("id", "name")
    )
);

// Using data from an array
echo $this->tag->selectStatic(
    array(
        "status",
        array(
            "A" => "Active",
            "I" => "Inactive",
        )
    )
);

The following HTML will generated:

<select id="productId" name="productId">
    <option value="101">Tomato</option>
    <option value="102">Lettuce</option>
    <option value="103">Beans</option>
</select>

<select id="status" name="status">
    <option value="A">Active</option>
    <option value="I">Inactive</option>
</select>

You can add an “empty” option to the generated HTML:

<?php

// Creating a Select Tag with an empty option
echo $this->tag->select(
    array(
        "productId",
        Products::find("type = 'vegetables'"),
        "using"    => array("id", "name"),
        "useEmpty" => true
    )
);

Produces this HTML:

<select id="productId" name="productId">
    <option value="">Choose..</option>
    <option value="101">Tomato</option>
    <option value="102">Lettuce</option>
    <option value="103">Beans</option>
</select>
<?php

// Creating a Select Tag with an empty option with default text
echo $this->tag->select(
    array(
        'productId',
        Products::find("type = 'vegetables'"),
        'using'      => array('id', "name"),
        'useEmpty'   => true,
        'emptyText'  => 'Please, choose one...',
        'emptyValue' => '@'
    )
);
<select id="productId" name="productId">
    <option value="@">Please, choose one..</option>
    <option value="101">Tomato</option>
    <option value="102">Lettuce</option>
    <option value="103">Beans</option>
</select>

Volt syntax for above example:

{# Creating a Select Tag with an empty option with default text #}
{{ select('productId', products, 'using': ['id', 'name'],
    'useEmpty': true, 'emptyText': 'Please, choose one...', 'emptyValue': '@') }}

设置 HTML 属性(Assigning HTML attributes)

All the helpers accept an array as their first parameter which can contain additional HTML attributes for the element generated.

<?php $this->tag->textField(
    array(
        "price",
        "size"        => 20,
        "maxlength"   => 30,
        "placeholder" => "Enter a price"
    )
) ?>

or using Volt:

{{ text_field("price", "size": 20, "maxlength": 30, "placeholder": "Enter a price") }}

The following HTML is generated:

<input type="text" name="price" id="price" size="20" maxlength="30"
    placeholder="Enter a price" />

设置助手的值(Setting Helper Values)

通过控制器(From Controllers)

It is a good programming principle for MVC frameworks to set specific values for form elements in the view. You can set those values directly from the controller using PhalconTag::setDefault(). This helper preloads a value for any helpers present in the view. If any helper in the view has a name that matches the preloaded value, it will use it, unless a value is directly assigned on the helper in the view.

<?php

use PhalconMvcController;

class ProductsController extends Controller
{
    public function indexAction()
    {
        $this->tag->setDefault("color", "Blue");
    }
}

At the view, a selectStatic helper matches the same index used to preset the value. In this case “color”:

<?php

echo $this->tag->selectStatic(
    array(
        "color",
        array(
            "Yellow" => "Yellow",
            "Blue"   => "Blue",
            "Red"    => "Red"
        )
    )
);

This will generate the following select tag with the value “Blue” selected:

<select id="color" name="color">
    <option value="Yellow">Yellow</option>
    <option value="Blue" selected="selected">Blue</option>
    <option value="Red">Red</option>
</select>

通过请求(From the Request)

A special feature that the PhalconTag helpers have is that they keep the values of form helpers between requests. This way you can easily show validation messages without losing entered data.

直接设置值(Specifying values directly)

Every form helper supports the parameter “value”. With it you can specify a value for the helper directly. When this parameter is present, any preset value using setDefault() or via request will be ignored.

动态设置文档标题(Changing dynamically the Document Title)

PhalconTag offers helpers to change dynamically the document title from the controller. The following example demonstrates just that:

<?php

use PhalconMvcController;

class PostsController extends Controller
{
    public function initialize()
    {
        $this->tag->setTitle("Your Website");
    }

    public function indexAction()
    {
        $this->tag->prependTitle("Index of Posts - ");
    }
}
<html>
    <head>
        <?php echo $this->tag->getTitle(); ?>
    </head>
    <body>

    </body>
</html>

The following HTML will generated:

<html>
    <head>
        <title>Index of Posts - Your Website</title>
    </head>

    <body>

    </body>
</html>

静态内容助手(Static Content Helpers)

PhalconTag also provide helpers to generate tags such as script, link or img. They aid in quick and easy generation of the static resources of your application

图片(Images)

<?php

// Generate <img src="/your-app/img/hello.gif">
echo $this->tag->image("img/hello.gif");

// Generate <img alt="alternative text" src="/your-app/img/hello.gif">
echo $this->tag->image(
    array(
       "img/hello.gif",
       "alt" => "alternative text"
    )
);

Volt syntax:

{# Generate <img src="/your-app/img/hello.gif"> #}
{{ image("img/hello.gif") }}

{# Generate <img alt="alternative text" src="/your-app/img/hello.gif"> #}
{{ image("img/hello.gif", "alt": "alternative text") }}

样式表(Stylesheets)

<?php

// Generate <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Rosario" type="text/css">
echo $this->tag->stylesheetLink("http://fonts.googleapis.com/css?family=Rosario", false);

// Generate <link rel="stylesheet" href="/your-app/css/styles.css" type="text/css">
echo $this->tag->stylesheetLink("css/styles.css");

Volt syntax:

{# Generate <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Rosario" type="text/css"> #}
{{ stylesheet_link("http://fonts.googleapis.com/css?family=Rosario", false) }}

{# Generate <link rel="stylesheet" href="/your-app/css/styles.css" type="text/css"> #}
{{ stylesheet_link("css/styles.css") }}

脚本(Javascript)

<?php

// Generate <script src="http://localhost/javascript/jquery.min.js" type="text/javascript"></script>
echo $this->tag->javascriptInclude("http://localhost/javascript/jquery.min.js", false);

// Generate <script src="/your-app/javascript/jquery.min.js" type="text/javascript"></script>
echo $this->tag->javascriptInclude("javascript/jquery.min.js");

Volt syntax:

{# Generate <script src="http://localhost/javascript/jquery.min.js" type="text/javascript"></script> #}
{{ javascript_include("http://localhost/javascript/jquery.min.js", false) }}

{# Generate <script src="/your-app/javascript/jquery.min.js" type="text/javascript"></script> #}
{{ javascript_include("javascript/jquery.min.js") }}

HTML5 对象(HTML5 elements - generic HTML helper)

Phalcon offers a generic HTML helper that allows the generation of any kind of HTML element. It is up to the developer to produce a valid HTML element name to the helper.

<?php

// Generate
// <canvas id="canvas1" width="300" class="cnvclass">
// This is my canvas
// </canvas>
echo $this->tag->tagHtml("canvas", array("id" => "canvas1", "width" => "300", "class" => "cnvclass"), false, true, true);
echo "This is my canvas";
echo $this->tag->tagHtmlClose("canvas");

Volt syntax:

{# Generate
<canvas id="canvas1" width="300" class="cnvclass">
This is my canvas
</canvas> #}
{{ tag_html("canvas", ["id": "canvas1", width": "300", "class": "cnvclass"], false, true, true) }}
    This is my canvas
{{ tag_html_close("canvas") }}

标签服务(Tag Service)

PhalconTag is available via the ‘tag’ service, this means you can access it from any part of the application where the services container is located:

<?php echo $this->tag->linkTo('pages/about', 'About') ?>

You can easily add new helpers to a custom component replacing the service ‘tag’ in the services container:

<?php

use PhalconTag;

class MyTags extends Tag
{
    // ...

    // Create a new helper
    static public function myAmazingHelper($parameters)
    {
        // ...
    }

    // Override an existing method
    static public function textField($parameters)
    {
        // ...
    }
}

Then change the definition of the service ‘tag’:

<?php

$di['tag'] = function () {
    return new MyTags();
};

创建助手(Creating your own helpers)

You can easily create your own helpers. First, start by creating a new folder within the same directory as your controllers and models. Give it a title that is relative to what you are creating. For our example here, we can call it “customhelpers”. Next we will create a new file titled MyTags.php within this new directory. At this point, we have a structure that looks similar to : /app/customhelpers/MyTags.php. In MyTags.php, we will extend the PhalconTag and implement your own helper. Below is a simple example of a custom helper:

<?php

use PhalconTag;

class MyTags extends Tag
{
    /**
     * Generates a widget to show a HTML5 audio tag
     *
     * @param array
     * @return string
     */
    static public function audioField($parameters)
    {
        // Converting parameters to array if it is not
        if (!is_array($parameters)) {
            $parameters = array($parameters);
        }

        // Determining attributes "id" and "name"
        if (!isset($parameters[0])) {
            $parameters[0] = $parameters["id"];
        }

        $id = $parameters[0];
        if (!isset($parameters["name"])) {
            $parameters["name"] = $id;
        } else {
            if (!$parameters["name"]) {
                $parameters["name"] = $id;
            }
        }

        // Determining widget value,
        // PhalconTag::setDefault() allows to set the widget value
        if (isset($parameters["value"])) {
            $value = $parameters["value"];
            unset($parameters["value"]);
        } else {
            $value = self::getValue($id);
        }

        // Generate the tag code
        $code = '<audio id="'.$id.'" value="'.$value.'" ';
        foreach ($parameters as $key => $attributeValue) {
            if (!is_integer($key)) {
                $code.= $key.'="'.$attributeValue.'" ';
            }
        }
        $code.=" />";

        return $code;
    }
}

After creating our custom helper, we will autoload the new directory that contains our helper class from our “index.php” located in the public directory.

<?php

use PhalconLoader;
use PhalconMvcApplication;
use PhalconDIFactoryDefault();
use PhalconException as PhalconException;

try {

    $loader = new Loader();
    $loader->registerDirs(array(
        '../app/controllers',
        '../app/models',
        '../app/customhelpers' // Add the new helpers folder
    ))->register();

    $di = new FactoryDefault();

    // Assign our new tag a definition so we can call it
    $di->set('MyTags', function () {
        return new MyTags();
    });

    $application = new Application($di);
    echo $application->handle()->getContent();

} catch (PhalconException $e) {
    echo "PhalconException: ", $e->getMessage();
}

Now you are ready to use your new helper within your views:

<body>

    <?php

    echo MyTags::audioField(
        array(
            'name' => 'test',
            'id'   => 'audio_test',
            'src'  => '/path/to/audio.mp3'
        )
    );

    ?>

</body>

In next chapter, we’ll talk about Volt a faster template engine for PHP, where you can use a more friendly syntax for using helpers provided by PhalconTag.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务