CakePHP中文教程5

来源:互联网 发布:逻辑回归算法知乎 编辑:程序博客网 时间:2024/05/20 05:05

第九章 Helpers

Helpers设计的目的是提供一些方法,views通过使用这些方法能够更好的规范和显示数据。

1.1 HTML

1.1.1 介绍

       HTML helper是Cake里快速开发,减少单调工作的一种途径。HTML helper有两个目的:为在HTML代码插入经常使用的代码提供帮助,为快速创建web form标单提供帮助。下面的这一节将会着重介绍这些方法,更多内容请参考http://api.cakephp.org

       在HTML helper中许多方法都使用的HTML tag都是定义在 tags.ini.php。Cake的核心库中包含了一个tags.ini.php,但是如果你想做些改动,请在/app/conifg下面创建一份/cake/config/tags.ini.php. HTML helper将会使用这个文件中的tag定义来生成你需要的tags。使用HTML helper来创建自己的view代码将会非常有用,因为tags.ini.php文件中的改动将会在整个站点上都有显示。

       另外,如果核心库文件(/app/config/core.php)中AUTO_OUTPUT被设置成true。hepler将会自动输出这些tag,而不是返回这些值。这样做是为了满足那些不喜欢在view中使用短标签(<?= ?>)或者许多echo()调用。包含$return参数的方法允许你该写自己的核心库配置。如果不考虑AUTO_OUTPUT的设置,你可以将$return设置为true这样html helper将会返回HTML代码。

       HTML helper方法同样包含了$htmlAttibutes参数,这个参数是的你可以将其他的属性粘贴在标签上。比如,你想给一个标签添加一个class属性,你可以把下面这个作为$htmlAttribute的属性。


array('class'=>'someClass')

1.1.2 插入正确组织的元素(well-formatted elements)

       如果你想要在你的HTMl代码中插入正确组织的、经常使用的元素,HTML helper起到很大的作用。这里有四个方法可以插入media,协助tables,甚至用可视化的列表树创建基于PHP数组的未排序的列表。

●charset($charset,$return)

    ○这个方法可以创建一个charset的meta标签(META-tag)

●css($path ,$rel =’stylesheet’ , $htmlAttriutes= null , $return =false)

       ○创建一个css模版页(stylesheet),$rel参数允许用户提供一个 rel=value作为标签(原文:The $rel parameter allows you to provide a rel= value for the tag.)

●image($path, $htmlAttributes =null, $return=false)

    ○显示一个图片的标签。返回的代码可以用做link()方法的输入,这样就可以自动的产生一个linked images(liuchen注:我的理解就是创建了一个可以点击的图片,链接到别处)

●link($title,$url=null,$htmlAttributes=null,$confirmMessage=false,

$escapeTitle=True, $return=false)

○使用这个方法可以在view里面创建一个链接,$confirmMessage可以在你需要一条javascript的确认信息的时候使用,这样,点击这个链接则跳出这个确认信息,一条删除对象的链接经常需要一条“你确定么?”的确认信息,这样在删除之前要求用户的确认。如果你想让HTML helper不用管理你的数据(保存在$title变量中),可以将$escapeTitle设置成为true

●tableHeaders($names,$tr_options=null,$th_options=null)

    ○用来创建格式化的表格头

●tableCells($data,$odd_tr_options=null,$even_tr_options=null)

    ○用来创建格式化的表格单元

●guiListTree($data,$htmlAttributes=null,$bodyKey=’body’,

                     $childrenKey=’children’,$return=false)

       ○根据一个数组创建一个未排序的整齐的列表

1.1.3 表格和正确性 (Forms and Validation)

Cake在view中快速编写html代码时候确实非常有效,它自动生成form标签,如果有错误还能自动填入值和错误消息。下面我们举个例子来实现。假设,你的程序有了一个Note model,你想创建一个controller逻辑和一个view来add和edit Note的对象。在你的NotesController中,你可以有一个edit action,这个action可以像下面这样:


function edit($id)
   {
      //First, let's check to see if any form data has been submitted to the action.     
      if (isset($this->params['form']['data']['note']))
      {
         //Here's where we try to validate the form data (see Chap. 10) and save it
         if ($this->note->save($this->params['data']))
         {
            //If we've successfully saved, take the user to the appropriate place
            $this->flash('Your information has been saved.', '/notes/edit/' . $id);
            exit();
         }
         else
         {
            //If the data didn't validate, hand the form data back to the view
            $this->set('form', $this->params['data']);           
            //Generate the error messages for the appropriate fields
            $this->validateErrors($this->note);
            //And render the edit view code
            $this->render();
         }     
      }     
      // If we haven't received any form data, get the note we want to edit, and hand
      // its information to the view
      $this->set('note', $this->note->find("id = $id"));
      $this->render();
   }


一旦我们的controller建立,我们来看一下view的代码(位于app/views/notes/edit.thtml)。我们的Note model是非常简单的。而且仅仅包含了一个id,一个提交着的id和body。这个view 的代码意思是显示Note的数据并且让用户输入新的值并将提交的新值输到model中。

       任何views默认情况下都可以得到HTML helper,使用$html就可以了。

       特别的,可以看下面的table

 

例9.2 Edit View code(edit.thtml)

 

<!-- This tag creates our form tag -->
<?php echo $html->formTag('/notes/edit/' . $note['note']['id'])?>
<table cellpadding="10" cellspacing="0">
<tr>
   <td align="right">Body: </td>
   <td>
      <!-- Here's where we use the HTML helper to render the text area tag and its possible error message the $note variable was created by the controller, and contains the data for the note we're editing. -->
      <?php echo
      $html->textarea('note/body', array('cols'=>'60', 'rows'=>'10',
           'value' => $note['note']['body']))
      ?>
      <?php echo $html->tagErrorMsg('note/body', 'Please enter in a body for this note.') ?>
   </td>
</tr>
<tr>
   <td></td>
   <td>
      <!-- We can also use the HTML helper to include hidden tags inside our table -->
      <?php echo $html->hiddenTag('note/id', $note['note']['id'])?>
      <?php echo $html->hiddenTag('note/submitter_id', $_SESSION['user_id'])?>
   </td>
</tr>
</table>
<!-- And finally, the submit button-->
<?php echo $html->submit()?>
</form>

大多数的表单标签生成方法(包括tagErrorMsg)都需要你提供一个$fieldName。这个$fieldName可以让Cakezhidao你想要传递什么数据,进而检查这个数据并保存。$fieldName参数传递的字符串要满足这种形式“modelname/fieldname”,如果你想要添加一个title field进入Note,你需要向view中添加下面这些代码
<?php echo $html->input('note/title', $note['note']['title']) ?>
<?php echo $html->tagErrorMsg('note/title', 'Please supply a title for this note.')?>

错误信息将会有tagErrorMsg()方法显示在<div class=”error_message”></div>这个标签中,使用简单的CSS模式

       下面是一些HTML helper可以创建的form tags(大多数都是直接创建)。

●formTag($target=null, $type=’post’,$htmlAttributes=null)

       ○创建一个打开的表单标签,使用$target来确定表单的action。记住,如果你要提交一个文件,你需要向$hatmAttrbutes参数提供合适的字符编码信息(?enctype infomation)

●submit($caption=’Submit’, $htmlAttributes=null, $return= false)

       ○通过$caption参数可以修改按钮名

●password($fieldName, $htmlAttributes=null, $return=false)

●textarea($fieldName, $htmlAttributes=null, $return = false)

●checkbox($fieldName, $title=null, $htmlAttributes=null, $return=false)

●file($fieldName, $htmlAttributes = null, $return=false)

●hidden($fieldName, $htmlAttributes=null, $return=false)

●input($fieldName, $htmlAttributes=null, $return=false)

●radio($fieldName,$options,$inbetween=null,$htmlAttributes=null,$return=false)

●tagErrorMsg($field, $text)

       HTML helper也包含了一系列方法来帮助创建数据库相关的tag。$tagName参数应该像$filedName参数一样处理。基金提供date option tag相关的field name.处理数据时,你可以在controller里面使用则各数据一直到该field的结尾。举例来说,如果我的Note有个deadline列(作为data),我的dayOptionTag $tagName参数被设置成‘note/deadline’,一旦表单被提交,day数据将作为$params变量显示出来 $this->params['form']['data']['note']['deadline_day']

你可以使用这个来连接你的时间数据到跟你当前数据库配置相符合的形式。这段代码可以放在你尝试保存数据之前,保存到$data数组,这个数组可以用来保存信息到model中

例9.3 Concatenating time data before saving a mode(excerpt from NotesController)   
function edit($id)
   {
      //First, let's check to see if any form data has been submitted to the action.     
      if (isset($this->params['form']['data']['note']))
      {
         //Concatenate time data for storage
         $this->params['data']['note']['deadline'] =
            $this->params['form']['data']['note']['deadline_year'] . "-" .
            $this->params['form']['data']['note']['deadline_month'] . "-" .
            $this->params['form']['data']['note']['deadline_day'];                          
         //Here's where we try to validate the form data (see Chap. 10) and save it
         if ($this->note->save($this->params['data']))
         {
        


●dayOptionTag ($tagName, $value=null, $selected=null, $optionAttr=null)

●yearOptionTag ($tagName, $value=null, $minYear=null, $maxYear=null,

$selected=null, $optionAttr=null)

●monthOptionTag ($tagName, $value=null, $selected=null, $optionAttr=null)

●hourOptionTag ($tagName, $value=null, $format24Hours=false,

$selected=null, $optionAttr=null)

●minuteOptionTag ($tagName, $value=null, $selected=null, $optionAttr=null)

●meridianOptionTag ($tagName, $value=null, $selected=null, $optionAttr=null)

●dateTimeOptionTag ($tagName, $dateFormat= 'DMY', $timeFormat= '12',

$selected=null, $optionAttr=null)

 

1.2 AJAX

Cake Ajax helper实现了更加popular的Prototype和script.aculo.us库赖提供Ajax操作和客户端效果。如果想使用这些helper,你必须有从http://script.aculo.us下载一份JavaScript libraries到/app/webroot/js目录下

这个helper里面的削夺方法多扩展了特殊的$options数组作为参数。这个数组用来确定你的Ajax操作中的各种东西

 

(liuchen:Ajax暂且略过,以后补充)

 

1.3 JavaScript

       JavaScript helper用来帮助开发者输出标准的tag和数据

●codeBlock($script)

       ○用来返回$script,变量$script已经包含了<script>标签

●link($url)

       ○返回包含tag,指向特定$url指定script的脚本

●linkOut($url)

       ○跟link($url)的作用一样,就是参数$url不在本地

●escapeScript($script)

       ○Escapes carriage returns and single and double quotes for JavaScript code segments.

●event($object, $event, $observer, $useCapture=true)

○使用Prototype库,将一个事件链接到一个元素

●cacheEvents()

○缓存event()创建的JavaScript事件

●writeEvents()

○写cacheEvent()保存的内容

●includeScript($script=””)

       ○返回含有标签的JavaScript,一般是从Cake的js库中(/app/webroot/js/)

 

1.4 Number

       Number helper包括一些在views中转化数字数据的方法

●precision ($number, $precision=3)

       ○返回由$precision确定的近似精度的值到$number中

●toReadableSize ($size)

       ○将bytes为单位的数字转化为用KB、MB、GB、TB等用户比较容易明白的数字

●toPercentage ($number, $precision=2)

○转化为百分数

 

1.5 Text

The Text Helper提供了一些方法,开发者可以使用这些方法来更好的将text输出到浏览器

●highlight ($text, $phrase, $highlighter= '< span class="highlight">/1</span >')

       ○将$text中所有$phrase都放在一个<span>标签里,返回$text

●stripLinks ($text)

       ○将所有的链接<a>标签都删除后返回

●autoLinkUrls ($text, $htmlOptions=array())

       ○将所有的URL自动添加<a>标签

●autoLinkEmails ($text, $htmlOptions=array())

       ○将所有的email地址自动添加<a>标签

●autoLink ($text, $htmlOptions=array())

       ○将所有的URL和email地址都自动添加<a>标签

●truncate ($text, $length, $ending='...')

       ○Returns the first $length number of characters of $text followed by $ending ('...' by default).(不明白)

●trim ()

○Alias for truncate().

●excerpt ($text, $phrase, $radius=100, $ending="...")

○Extracts an excerpt from the $text, grabbing the $phrase with a number of characters on each side determined by $radius.

●flay($text, $allowHtml=false)

○Text-to-html parser, similar to Textile or RedCloth, only with a little different syntax.

 

 

1.6 Time

Time Helper提供了一些方法,卡发者可以使用这些方法将时间方便的显示到浏览器上。时间可以提供的形式包括PHP的datatime字符串或者是Unix的时间戳

●fromString ($date_string)

       ○根据输入的两种类型的时间返回Unix时间戳

●nice ($date_string=null, $return=false)

       ○返回一个良好格式的时间字符串。比如Mon, Jan 1st 2005, 12:00

●niceShort ($date_string=null, $return=false)

○跟nice类似,就是返回昨天和今天的时候,返回Yesterday, 12:00和Today, 12:00

●isToday ($date_string)

       ○返回给定的时间是否是今天

●daysAsSql ($begin, $end, $field_name, $return=false)

       ○根据前后两个时间,返回一条sql查询语句,查找两个时间段内的记录

●dayAsSql ($date_string, $field_name, $return=false)

       ○返回给定时间内的所有记录

●isThisYear ($date_string, $return=false)

       ○返回是否是今年

●wasYesterday ($date_string, $return=false)

       ○返回是否是去年

●isTomorrow ($date_string, $return=false)

       ○返回是否是明天

●toUnix ($date_string, $return=false)

       ○返回Unix时间戳

●toAtom ($date_string, $return=false)

○Returns a date formatted for Atom RSS feeds.

●toRSS ($date_string, $return=false)

○格式化的RSS时间

●timeAgoInWords ($datetime_string, $return=false)

       ○Returns either a relative date or a formatted date depending on the difference between the current time and given datetime. $datetime should be in a strtotime-parsable format like MySQL datetime.

●relativeTime ($datetime_string, $return=false)

○Works much like timeAgoInWords(), but includes the ability to create output for timestamps in the future as well (i.e. "Yesterday, 10:33", "Today, 9:42", and also "Tomorrow, 4:34").

●wasWithinLast ($timeInterval, $date_string, $return=false)

       ○Returns true if specified datetime was within the interval specified, else false. The time interval should be specifed with the number as well as the units: '6 hours', '2 days', etc.

 

 
原创粉丝点击