Archive for the ‘PHP’ category

smarty3的一些实用的新特性

October 14th, 2010

表达式

支持更加随意的表达式

{$x+$y}                           输入x和y的和
{$foo = strlen($bar)}             变量支持PHP函数
{assign var=foo value= $x+$y}     属性支持表达式
{$foo = myfunct( ($x+$y)*3 )}     函数参数支持表达式
{$foo[$x+3]}                      数组下表支持表达式


可以在Smarty标签使用其他标签的值
{$foo="this is message {counter}"}

可以在双引号里使用Smarty标签

{$foo="this is message {counter}"}

双引号中可以使用变量,也可以使用Smarty标签

{$foo="this is message $counter"}

{func var="test $foo test"} // 同$foo
{func var="test $foo_bar test"} // 同$foo_bar
{func var="test `$foo[0]` test"} // 同$foo[0]
{func var="test `$foo[bar]` test"} // 同$foo[bar]
{func var="test $foo.bar test"} // 同$foo (而不是$foo.bar)
{func var="test `$foo.bar` test"} // 同$foo.bar
{func var="test `$foo.bar` test"|escape} // 引号外加修饰符
{func var="test {$foo|escape} test"} // 引号内加修饰符
{func var="test {time()} test"} // 调用PHP方法
{func var="test {counter} test"} // 调用插件返回值
{func var="variable foo is {if !$foo}not {/if} defined"} // 调用Smarty block方法

{* 将会替换$tpl_name为对应的值*}
{include file="subdir/$tpl_name.tpl"}
{* 不会替换$tpl_name *}
{include file='subdir/$tpl_name.tpl'} // 变量需要用双引号才可以解析!
{* 用点号"."的话必须加反引号 *}
{cycle values="one,two,`$smarty.config.myval`"}
{* 用点号"."的话必须加反引号 *}
{include file="`$module.contact`.tpl"}
{* 用点号语法可以使用变量 *}
{include file="`$module.$view`.tpl"}

可以在模板里头定义数组

{assign var=foo value=[1,2,3]}
{assign var=foo value=['y'=>'yellow','b'=>'blue']}
{assign var=foo value=[1,[9,8],3]}   数组可以嵌套

简单的变量赋值

{$foo=$bar+2}

可以给指定的数组元素赋值,如果变量存在但不是数组,会先转换成数组,再进行赋值
{$foo['bar']=1}
{$foo['bar']['blar']=1}

同上,可以给数组添加值

{$foo[]=1}

点号.功能更强大:支持变量索引、支持表达式索引、支持嵌套索引
{$foo.a.b.c}        =>  $foo['a']['b']['c']
{$foo.a.$b.c}       =>  $foo['a'][$b]['c']        支持变量索引
{$foo.a.{$b+4}.c}   =>  $foo['a'][$b+4]['c']       支持表达式索引
{$foo.a.{$b.c}}     =>  $foo['a'][$b['c']]         支持嵌套索引

变量名中支持变量

$foo         一个普通的变量
$foo_{$bar}  变量名中包含变量
$foo_{$x+$y} 变量名中可以支持表达式
$foo_{$bar}_buh_{$blar}  变量名包含多个变量
{$foo_{$x}}  如果$x是1,则输出$foo_1

支持对象链,即是对象方法的连续调用,很像jquery

{$object->method1($x)->method2($y)}

{for}标签支持类似loop一样的循环

{for $x=0, $y=count($foo); $x<$y; $x++}  ....  {/for}

在FOR循环中可以通过如下特殊标示符限定位置:

$x@iteration  当前循环次数
$x@total     总循环次数
$x@first  循环第一次
$x@last     循环最后一次

新的foreach语法

{foreach $myarray as $var}...{/foreach}

同样是foreach里头的特殊表示符,看的就明白,不翻译了……

$var@key            foreach $var array key
$var@iteration      foreach current iteration count (1,2,3...)
$var@index          foreach current index count (0,1,2...)
$var@total          foreach $var array total
$var@first          true on first iteration
$var@last           true on last iteration

支持while循环

{while $foo}...{/while}
{while $x lt 10}...{/while}

可以直接使用PHP的函数

{time()}

支持将字符串作为模板显示:使用string的资源类型即可:
$smarty->display('string:This is my template, {$foo}!'); // php
{include file="string:This is my template, {$foo}!"} // template
支持纯php的模板:完全以php语法书写的模板,调用时使用php的资源类型即可:$smarty->display(‘php:foo.php’);
当然也可以{include file=”php:foo.php”},
不过在纯php的模板中是无法调用smarty的modifier/function的,以后的版本也许会考虑封装

模板继承:类似类的继承,可以继承父模板文件,同时重载父模板中相同name的{block}区块内容
静态类,命名空间的支持:可以这样注册一个静态类,其中命名空间可选
$smarty->register->templateClass(‘foo’,'name\name2\myclass’);
在模板中调用:
{foo::method()}

参考:http://www.emptykid.com/blog/archives/133

http://shameerc.wordpress.com/2010/10/06/an-introduction-to-smarty-3/

  • Share/Save/Bookmark

array_map的一个特殊应用

October 12th, 2009

通常array_map用来做回调函数,不过在手册中有一个特殊的应用:

将每个数组对应的key的值进行组合生成一个数组,并将所有的值的数组组合成一个2维数组

Example #4 Creating an array of arrays

<?php
$a
= array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");

$d = array_map(null, $a, $b, $c);
print_r($d);
?>

The above example will output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
            [2] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
            [2] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => four
            [2] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => five
            [2] => cinco
        )

)

Example #5 array_map() - with string keys
$arr = array("stringkey" => "value");
var_dump(array_map(null, $arr));
var_dump(array_map(null, $arr, $arr));

array(1) {
  ["stringkey"]=>
  string(5) "value"
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "value"
    [1]=>
    string(5) "value"
  }
}

  • Share/Save/Bookmark

Zend Studio 7.0 EA 发布!

May 21st, 2009

刚“升”到6.1.2,这7.0又快出了,直接一个版本的跳跃,看来是要修正好多问题,其实最主要的还是要跟进PHP5.3吧,提供的特性都挺方便的,不过暂时开发用的还是5.2.9,所以先关注下,等正式版出来再继续“升”吧。。。

———————以下为官方的发布介绍的部分翻译———————–

Zend Studio 7.0 Early Access (EA) 提供了一些7.0新增特性和改进的预览

这些特性并没有全部完成,但是可以提前预览下这些即将到来的新特性

点此反馈和提交bug

Zend Studio 7.0 基于Eclipse 的最新版本(Galileo).

注意:虽然开发人员尽量使这个版本保持稳定,但是毕竟是EA版本,请小心使用,不要用在任何线上产品上。

点此下载

Zend Studio 7.0有哪些新特性?

What’s New in Zend Studio 7.0?

支持PHP 5.3

支持PHP的最新特性,比如namespaces(命名空间)和lambda functions(匿名函数):

  • PHP 5.3 特性的代码提示和语法高亮
  • Namespace 大纲
  • 捆绑了 PHP 可执行和调试功能

加强的源码编辑功能

Enhanced Source Code Editing

拥有更强大的面向对象的编辑功能

  • 标示来源 of Language Elements, Exit Paths and Requires
  • 重载指示 for quick navigation between methods
  • 类型阶级 view for structured class hierarchy
  • Open Type / Method with Camel-Case Match
  • Code Assist Grouping
  • Inline Refactoring for fast element renaming
  • Develop modular applications with Build and Include Path features
  • Turn a block of code into a function or a variable with Extract Variable / Method
  • Semantic Analysis and Auto Fix

集成Zend Server进行快速的本地调试

Quick Root Cause Analysis through Zend Server Integration

Tight integration with Zend Server for easy debugging and problem resolution

  • Auto Detection and configuration of the local Zend Server
  • Easy Deployment to Local Server
  • Easy Debug setup
  • List View of Associated Servers
  • Quick launch of Zend Server Events List
  • Debug Imported Events

快速的Zend Framework应用开发

Rapid Application Development with Zend Framework

Integration with Zend Tool and code generation for rapid application development

  • Easy Creation of Zend Framework Elements
  • Customized Zend Framework Project Layout
  • Updated Zend Framework Example Project
  • Code generation through Zend Tool integration

更好的性能

Better Performance

  • Reduced memory footprint with better workspace modeling
  • Use of Eclipse Indexing and Caching architecture
  • Removed unneeded dependencies

如何进行反馈

访问 Zend Forums 进行反馈,提问或者提交bug

Zend Studio的更新提示

Get Notified on Zend Studio Updates

Make sure you sign up for the Zend PHP Update Email to receive information about Zend Studio, tips and tricks, PHP development best practices and more.

  • Share/Save/Bookmark

header中的Cache-control参数说明

May 10th, 2009

网页的缓存是由HTTP消息头中的“Cache-control”来控制的,常见的取值有private、no-cache、max-age、must-revalidate等,默认为private。其作用根据不同的重新浏览方式分为以下几种情况:

(1) 打开新窗口
值为private、no-cache、must-revalidate,那么打开新窗口访问时都会重新访问服务器。
而如果指定了max-age值,那么在此值内的时间里就不会重新访问服务器,例如:
Cache-control: max-age=5(表示当访问此网页后的5秒内再次访问不会去服务器)

(2) 在地址栏回车
值为private或must-revalidate则只有第一次访问时会访问服务器,以后就不再访问。
值为no-cache,那么每次都会访问。
值为max-age,则在过期之前不会重复访问。

(3) 按后退按扭
值为private、must-revalidate、max-age,则不会重访问,
值为no-cache,则每次都重复访问

(4) 按刷新按扭
无论为何值,都会重复访问

Cache-control值为“no-cache”时,访问此页面不会在Internet临时文章夹留下页面备份。

另外,通过指定“Expires”值也会影响到缓存。例如,指定Expires值为一个早已过去的时间,那么访问此网时若重复在地址栏按回车,那么每次都会重复访问: Expires: Fri, 31 Dec 1999 16:00:00 GMT

比如:禁止页面在IE中缓存

http响应消息头部设置:

CacheControl = no-cache
Pragma=no-cache
Expires = -1

Expires是个好东东,如果服务器上的网页经常变化,就把它设置为-1,表示立即过期。如果一个网页每天凌晨1点更新,可以把Expires设置为第二天的凌晨1点。

当HTTP1.1服务器指定CacheControl = no-cache时,浏览器就不会缓存该网页。

旧式 HTTP 1.0 服务器不能使用 Cache-Control 标题。
所以为了向后兼容 HTTP 1.0 服务器,IE使用Pragma:no-cache 标题对 HTTP 提供特殊支持。
如果客户端通过安全连接 (https://)与服务器通讯,且服务器在响应中返回 Pragma:no-cache 标题,
则 Internet Explorer不会缓存此响应。注意:Pragma:no-cache 仅当在安全连接中使用时才防止缓存,如果在非安全页中使用,处理方式与 Expires:-1相同,该页将被缓存,但被标记为立即过期

header常用指令
header分为三部分:
第一部分为HTTP协议的版本(HTTP-Version);
第二部分为状态代码(Status);
第三部分为原因短语(Reason-Phrase)。

// fix 404 pages:   用这个header指令来解决URL重写产生的404 header
header(’HTTP/1.1 200 OK’);

// set 404 header:   页面没找到
header(’HTTP/1.1 404 Not Found’);

//页面被永久删除,可以告诉搜索引擎更新它们的urls
// set Moved Permanently header (good for redrictions)
// use with location header
header(’HTTP/1.1 301 Moved Permanently’);

// 访问受限
header(’HTTP/1.1 403 Forbidden’);

// 服务器错误
header(’HTTP/1.1 500 Internal Server Error’);

// 重定向到一个新的位置
// redirect to a new location:
header(’Location: http://www.example.org/‘);

延迟一段时间后重定向
// redrict with delay:
header(’Refresh: 10; url=http://www.example.org/’);
print ‘You will be redirected in 10 seconds’;

// 覆盖 X-Powered-By value
// override X-Powered-By: PHP:
header(’X-Powered-By: PHP/4.4.0′);
header(’X-Powered-By: Brain/0.6b’);

// 内容语言 (en = English)
// content language (en = English)
header(’Content-language: en’);

//最后修改时间(在缓存的时候可以用到)
// last modified (good for caching)
$time = time() – 60; // or filemtime($fn), etc
header(’Last-Modified: ‘.gmdate(’D, d M Y H:i:s’, $time).’ GMT’);

// 告诉浏览器要获取的内容还没有更新
// header for telling the browser that the content
// did not get changed
header(’HTTP/1.1 304 Not Modified’);

// 设置内容的长度 (缓存的时候可以用到):
// set content length (good for caching):
header(’Content-Length: 1234′);

// 用来下载文件:
// Headers for an download:
header(’Content-Type: application/octet-stream’);
header(’Content-Disposition: attachment; filename=”example.zip”‘);
header(’Content-Transfer-Encoding: binary’);

// 禁止缓存当前文档:
// load the file to send:readfile(’example.zip’);
// Disable caching of the current document:
header(’Cache-Control: no-cache, no-store, max-age=0, must-revalidate’);
header(’Expires: Mon, 26 Jul 1997 05:00:00 GMT’);

// 设置内容类型:
// Date in the pastheader(’Pragma: no-cache’);
// set content type:
header(’Content-Type: text/html; charset=iso-8859-1′);
header(’Content-Type: text/html; charset=utf-8′);

// plain text file
header(’Content-Type: text/plain’);

// JPG picture
header(’Content-Type: image/jpeg’);

// ZIP file
header(’Content-Type: application/zip’);

// PDF file
header(’Content-Type: application/pdf’);

// Audio MPEG (MP3,…) file
header(’Content-Type: audio/mpeg’);

// flash file
header(’Content-Type: application/x-shockwave-flash’);

// 显示登录对话框,可以用来进行HTTP认证
// Flash animation// show sign in box
header(’HTTP/1.1 401 Unauthorized’);
header(’WWW-Authenticate: Basic realm=”Top Secret”‘);
print ‘Text that will be displayed if the user hits cancel or ‘;
print ‘enters wrong login data’;?>

  • Share/Save/Bookmark

php syntax exam

March 3rd, 2009

http://www.blueshoes.org/en/developer/syntax_exam/

在php手册中看到类型比较的时候发现的这个exam,正好测试了下基础,错了几个记录下来

21. $x = (array(’a'=>’foo’) == array(’b'=>’foo’));
what is $x?
you said: TRUE
right is: FALSE
好吧,我以为这两个数组比较时值都是ARRAY的说,其实两个数组在比较时并不是转换成字符进行比较的
array与array的比较,具有较少成员的数组较小,如果运算数 1 中的键不存在于运算数 2 中则数组无法比较,否则挨个值比较

22.$arrOne = array(”=>”);
$arrTwo = array(’9′=>’apple’, ‘15′=>’banana’, ‘20′=>’grapefruit’);
$x = array_merge($arrOne, $arrTwo);
what is $x?
1) array(”=>”, 0=>’apple’, 1=>’banana’, 2=>’grapefruit’);
2) array(”=>”, 9=>’apple’, 15=>’banana’, 20=>’grapefruit’);
you said: 2
right is: 1
具体见array_merge函数
如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。
如果你想完全保留原有数组并只想新的数组附加到后面,用 + 运算符。

50. $x = (bool)(”hello” == TRUE);
what is $x?
you said: FALSE
right is: TRUE
result: wrong
恩,比较运算符里有详细说明:
string,resource 或 number与string,resource 或 number比较时, 将字符串和资源转换成数字,按普通数学比较。

59. $a = “hello”;
$b = &$a;
unset($b);
$b = “world”;
what is $a?
you said: world
right is: hello

60. $a = “hello”;
$b = &$a;
unset($b);
what is $a?
you said: null
right is: hello

61. $a = “hello”;
$b = &$a;
$b = “world”;
unset($b);
what is $a?
you said: null
right is: world

好吧,引用后的变量unset不会影响到被引用的变量恩,我一直以为是$b指向$a,实际上是$b和$a指向了同一个地方(即变量内容)而已
在 PHP 中引用意味着用不同的名字访问同一个变量内容。这并不像 C 的指针,替代的是,引用是符号表别名。注意在 PHP 中,变量名和变量内容是不一样的,因此同样的内容可以有不同的名字。
当 unset 一个引用,只是断开了变量名和变量内容之间的绑定。这并不意味着变量内容被销毁了。

66. $a = ‘foo’;
$b = isSet($a['bar']);
what is $b?
you said: FALSE
right is: TRUE
result: wrong
‘bar’ in $a['bar'] evaluates to int 0 (see the PHP Cheat Sheet at http://www.blueshoes.org/en/developer/php_cheat_sheet/). Then it is $a[0] and now each character in the string $a (foo) can be accessed with its char number, like an array. So that is an ‘f’. And that thing is set.
这个我以前是真的没注意。。。记下了

其实对于字符串和字符串的比较,觉得文档上的有点问题,字符串和字符串比较时并不会转换成数字进行比较,只有当其中这两个字符串都为数字字符串时才会作为证书比较。不过对于66中的转换以前还真没注意TAT

  • Share/Save/Bookmark