Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

4/07/2009

Install Zend Server on Ubuntu 8.10

1 Add Zend server source list


deb http://repos.zend.com/deb/pe pe non-free

get public key and import it by sofware management editor

wget http://repos.zend.com/deb/zend.key


2 Set apache2's config to your workspace

The apache used by Zend Server is apache2,the config file locates in /etc/apache/
2.1 edit "/etc/apache2/sites-available/default"

<VirtualHost *:80>
ServerName localhost
ServerAdmin webmaster@localhost

DocumentRoot /home/edwin/Zend/workspaces/Odour-main/Public/
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /home/edwin/Zend/workspaces/Odour-main/Public/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>

ErrorLog /var/log/apache2/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog /var/log/apache2/access.log combined

Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
Options Indexes MultiViews FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>

</VirtualHost>

2.2 edit first virtualHost (IP:192.168.6.1)


<VirtualHost 192.168.6.1:80>
ServerName ComServer
ServerAdmin webmaster@localhost

DocumentRoot /home/edwin/Zend/comWorkspace/Public/
<Directory /home/edwin/Zend/comWorkspace/Public/>

Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>

ErrorLog /var/log/apache2/192.168.6.1.error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog /var/log/apache2/192.168.6.1.access.log combined
</VirtualHost>



3 enable virturalHost


sudo a2ensite 192.168.6.1


4 restart the apache

11/16/2008

if 和 switch 语句效率比较

在 switch 语句中条件只求值一次并用来和每个 case 语句比较。在 elseif 语句中条件会再次求值。如果条件比一个简单的比较要复杂得多或者在一个很多次的循环中,那么用 switch 语句可能会快一些。

以上为 php 手册在叙述 switch 中的一句,该怎么理解呢?

从整体效率上看,是相当的。但区别存在于呢?举个例子


if ($noizy==1) {

echo "noizy1";

} elseif ($noizy==2) {

echo "noizy2";

} elseif ($noizy==3) {

echo "noizy3";

}

以上是 if 代码的一个片段,在最差的状况下,也就是当 $noizy = 3 时,共运行了3次比较,而且,每次比较都必须取出 $noizy 的值一次。如果换成 switch

switch ($noizy) {
case 1:
echo "1";
break;
case 2:
echo "2";
break;
case 3:
echo "3";
break;
}

只在开头 switch 的括号中取出 $noizy 的值,然后把值与case值逐一进行比较

效率的差别就在这儿,因此我总结几点:

1.当只进行一次比较时,推荐使用 if,原因很简单,此时 if 与 switch 没有本质区别,而用 if 代码较为简洁,省去多余字节,可乐而不为?
2.当多次纯粹的比较数字或字符时,推荐使用 switch,当进行N次比较,switch 只取值一次,而 if …… elseif 则取值 1 <= x <= N (x 为实际次数)。
3.当遇到复合条件时,应该视情况而灵活运用 if 与 switch。

11/06/2008

Singleton pattern in PHP 5

1类别: 创建型设计模式
2意图: 确保一个类只有一个实例,而且自行向整个系统提供这一个实例(类本身提供一个实例的全局访问点)
3代码:


class Singleton {
// 用静态变量来存储signleton的实例
private static $_instance;
// 私有的构造器阻止New
private function __construct() {
...
}

// 避免除了New外,用户可以通过clone和序列化来获得多个singleton的实例
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public function __wakeup() {
trigger_error('Deserializing is not allowed.', E_USER_ERROR);
}
//用layz load 的方法,获得唯一实例
public static function getInstance() {
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
//singleton的实际作用
public function doAction() {
...
}
}

//usage
Singleton::getInstance()->doAction();

?>






更多: http://www.tonymarston.net/php-mysql/singleton.html
http://en.wikipedia.org/wiki/Singleton_pattern

9/13/2008

Many tips for optimize your php code

1。 If a method can be static, declare it static。 Speed improvement is by a factor of 4。 如果一个方法可静态化,就对它做静态声明。速率可提升至4倍。

2。 echo is faster than print。 echo 比 print 快。

3。 Use echo’s multiple parameters instead of string concatenation。 使用echo多重参数(译注:指用逗号而不是句点)代替字符串连接。

4。 Set the maxvalue for your for-loops before and not in the loop。 在执行for循环之前确定最大循环数,不要每循环一次都计算最大值。

5。 Unset your variables to free memory, especially large arrays。 注销那些不用变量尤其是大数组,以便释放内存。

6。 Avoid magic like __get, __set, __autoload 尽量避免使用__get,__set,__autoload。

7。 require_once() is expensive 少用require_once()

8。 Use full paths in includes and requires, less time spent on resolving the OS paths。 在包含文件时使用完整路径,解析操作系统路径所需时间会更少。

9。 If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time() 如果你想知道脚本开始执行时刻,使用$_SERVER[‘REQUEST_TIME’]要好于 time()。

10。 See if you can use strncasecmp, strpbrk and stripos instead of regex。 检查是否能用strncasecmp,strpbrk,stripos函数代替正则表达式完成相同功能。

11。 str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4。 str_replace函数比preg_replace函数快,但strtr函数效率是str_replace函数(9php.com)四倍。

12。 If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments。如果一个字符串替换函数,可接受数组或字符作为参数,并且参数长度不太长,那么可以考虑额外写一段替换代码,使得每次传递参数是一个字符,而不是只写一行代码接受数组作为查询和替换参数。

13。 It’s better to use select statements than multi if, else if, statements。 使用选择分支语句好于使用多个if,else if语句。

14。 Error suppression with @ is very slow。 用@屏蔽错误消息做法非常低效。

15。 Turn on apache’s mod_deflate 打开apachemod_deflate模块。

16。 Close your database connections when you’re done with them。 数据库连接当使用完毕时应关掉。

17。 $row[’id’] is 7 times faster than $row[id]。 $row[‘id’]效率是$row[id]7倍。

18。 Error messages are expensive。 错误消息代价昂贵。

19。 Do not use functions inside of for loop, such as for ($x=0; $x < x="0;">prop++) is 3 times slower than a local variable。 递增一个对象属性(如:$this->prop++)要比递增一个局部变量慢3倍。

23。 Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one。递增一个未预定义局部变量要比递增一个预定义局部变量慢9至10倍。

24。 Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var)。 PHP probably does a check to see if the global exists。仅定义一个局部变量而没在函数中调用它,同样会减慢速度(其程度相当于递增一个局部变量)。PHP大概会检查看是否存在全局变量。

25。 Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance。方法调与类中定义方法数量无关

26。 Methods in derived classes run faster than ones defined in the base class。 派生类中方法运行起来要快于在基类中定义同样方法。

27。 A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations。 A similar method call is of course about 15 $localvar++ operations。调用带有一个参数空函数,其花费时间相当于执行7至8次局部变量递增操作。类似 方法调用所花费时间接近于15次局部变量递增操作。

28。 Surrounding your string by ‘ instead of " will make things interpret a little faster since php looks for variables inside "…" but not inside ‘…’。 Of course you can only do this when you don’t need to have variables in the string。用单引号代替双引号来包含字符串,这样做会更快一些。因为PHP会在双引号包围字符串中搜寻变量,单引号则不会。当然,只有当你不需要在字符串中包含变量时才可以这么做。

29。 When echoing strings it’s faster to separate them by comma instead of dot。 Note: This only works with echo, which is a function that can take several strings as arguments。输出多个字符串时,用逗号代替句点来分隔字符串,速度更快。注意:只有echo能这么做,它是一种可以把多个字符串当作参数“函数 ”(译注:PHP手册中说echo是语言结构,不是真正函数,故把函数加上了双引号)。

30。 A PHP script will be served at least 2-10 times slower than a static HTML page by Apache。 Try to use more static HTML pages and fewer scripts。 Apache解析一个PHP脚本时间要比解析一个静态HTML页面慢2至10倍。尽量多用静态HTML页面,少用脚本。

31。 Your PHP scripts are recompiled every time unless the scripts are cached。 Install a PHP caching product to typically increase performance by 25-100% by removing compile times。除非脚本可以缓存,否则每次调用时都会重新编译一次。引入一套PHP缓存机制通常可以提升25%至100%性能,以免除编译开销。

32。 Cache as much as possible。 Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load。 OP code caches are useful so that your script does not have to be compiled on every request。尽量做缓存,可使用memcached。memcached是一款高性能内存对象缓存系统,可用来加速动态Web应用程序,减轻数据库负载。对运算码缓存很有用,使得脚本不必为每个请求做重新编译。

33。 When working with strings and you need to check that the string is either of a certain length you’d understandably would want to use the strlen() function。 This function is pretty quick since it’s operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP)。 However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function。 In some instance you can improve the speed of your code by using an isset() trick。当操作字符串并需要检验其长度是否满足某种要求时,你想当然地会使用strlen()函数。此函数执行起来相当快,因为它不做任何计算,只返回在zval 结构(C内置数据结构,用于存储PHP变量)中存储已知字符串长度。但是,由于strlen()是函数,多多少少会有些慢,因为函数调用会经过诸多步骤,如字母小写化(译注:指函数名小写化,PHP不区分函数名大小写)、哈希查找,会跟随被调用(函数一起执行。在某些情况下,你可以使用isset()技巧加速执行你代码。

举例如下
if (strlen($foo) < 5) { echo "Foo is too short"; } 与下面做比较 if (!isset($foo{5})) { echo "Foo is too short"; } Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it’s execution does not require function lookups and lowercase。 This means you have virtually no overhead on top of the actual code that determines the string’s length。调用isset()恰巧比strlen()快,因为与后者不同是,isset()作为一种语言结构,意味着它执行不需要函数查找和字母小写化。也就是说,实际上在检验字符串长度顶层代码中你没有花太多开销。 34。 When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i。 This is something PHP specific and does not apply to other languages, so don’t go modifying your C or Java code thinking it’ll suddenly become faster, it won’t。 ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3。 Post incrementation actually causes in the creation of a temporary var that is then incremented。 While pre-incrementation increases the original value directly。 This is one of the optimization that opcode optimized like Zend’s PHP optimizer。 It is still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer。当执行变量$i递增或递减时,$i++会比++$i慢一些。这种差异是PHP特有,并不适用于其他语言,所以请不要修改你C或Java代码并指望它们能立即变快,没用。++$i更快是因为它只需要3条指令 (opcodes),$i++则需要4条指令。后置递增实际上会产生一个临时变量,这个临时变量随后被递增。而前置递增直接在原值上递增。这是最优化处理一种,正如ZendPHP优化器所作那样。牢记这个优化处理不失为一个好主意,因为并不是所有指令优化器都会做同样优化处理,并且存在大量没有装配指令优化器互联网服务提供商(ISPs)和服务器。 35。 Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory。并不是事必面向对象(OOP),面向对象往往开销很大,每个方法和对象调用都会消耗很多内存。 36。 Do not implement every data structure as a class, arrays are useful, too。 并非要用类实现所有数据结构,数组也很有用。 37。 Don’t split methods too much, think, which code you will really re-use。 不要把方法细分得过多,仔细想想你真正打算重用是哪些代码? 38。 You can always split the code of a method later, when needed。 当你需要时,你总能把代码分解成方法。 39。 Make use of the countless predefined functions。 尽量采用大量PHP内置函数。 40。 If you have very time consuming functions in your code, consider writing them as C extensions。如果在代码中存在大量耗时函数,你可以考虑用C扩展方式实现它们。 41。 Profile your code。 A profiler shows you, which parts of your code consumes how many time。 The Xdebug debugger already contains a profiler。 Profiling shows you the bottlenecks in overview。评估检验(profile)你的代码。检验器会告诉你,代码哪些部分消耗了多少时间。Xdebug调试器包含了检验程序,评估检验总体上可以显示出代码瓶颈。 42。 mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%。 mod_zip可作为Apache模块,用来即时压缩你数据,并可让数据传输量降低80%
更多

5/03/2008

MySQL的日期和时间类型+PHP中的日期和时间函数

1. MySQL的日期时间列类型:
a. YEAR[(2|4)]

取值范围:2位为70-69 表示1970-2069; 4位表示1901-2155;
b. DATE
范围:1000-01-01到9999-12-31 格式为YYYY-MM-DD
c. TIME
范围:-838:59:59到838:59:59,格式为HH:MM:SS,注意其范围比想象的宽的多
d. DATETIME
范围:1000-01-01 00:00:00到9999-12-31 23:59:59,表示日期和时间,格式为

YYYY-MM-DD HH:MM:SS
e. TIMESTAMP[(M)]
范围:1970-01-01 00:00:00到2037年,表示格式有多种决定与M值:
TIMESTAMP: YYYYMMDDHHMMSS (14
位默认)
TIMESTAMP(14): YYYYMMDDHHMMSS
TIMESTAMP(12): YYMMDDHHMMSS
TIMESTAMP(10): YYMMDDHHMM
TIMESTAMP(8): YYYYMMDD
TIMESTAMP(6): YYMMDD
TIMESTAMP(4): YYMM
TIMESTAMP(2): YY

使用这些类型:

如果仅保存年使用YEAR;
保存日期使用DATE;
保存时间使用TIME;
保存日期和时间使用DATETIME或者TIMESTAMP;
另外注意取值范围

2. PHP中的日期和时间函数
1
)Unix timestamp:
Unix timestamp
表示把日期和时间转换为秒表示(距离Jan 01 1970时间差)

参考http://www.unixtimestamp.com/
尽管这种方法计算时间比较方便,但是面临最大值问题即若达到January 19, 2038将会出现32位溢出。
2
)PHP中常用的日期和时间函数:
尤其注意这里的timestamp为Unix timestamp即为距离1970-01-01的秒数。
和之前介绍的MySQL中的TIMESTAMP类型不同

(TIMESTAMP类型都是YYYYMMDDHHMMSS的格式,而不是秒数)
a. date(format,timestamp):
能够获取当前时间或者将已有的timestamp,转化为各种格式,通过format字符串可以定义格式。参考http://www.w3schools.com/php/func_date_date.asp
b। getdate(timestamp):
能够获取当前时间或者将已有的timestamp,转化为一个array
参考http://www.w3schools.com/php/func_date_getdate.asp
c। mktime(hour,minute,second,month,day,year,is_dst):
获取现在时间或者将已有的时间转换为timestamp
http://www.w3schools.com/php/func_date_mktime.asp
d. time()
获取当前时间的timestamp形式
http://www.w3schools.com/php/func_date_time.asp

3. 小结:
1
)
使用日期和时间,MySQL中的类型可以用DATETIME或者TIMESTAMP
两者分别保存为YYYY-MM-DD HH:MM:SS和YYYYMMDDHHMMSS等
在PHP方面可以使用date(format, timestamp)函数配合使用,因为date函数能够设置format将日期转化为符合DATETIME或者TIMESTAMP的格式保存起来。

2
)另一方面,在PHP中要习惯使用Unix timestamp这种形式的日期和时间,因为很方便计算,而且有很多函数方便使用。如果直接保存Unix timestamp可以将MySQL中的列类型定义为int(12)类似的整型就可以。

从PHP 5.1开始,date/time函数有一些变化,其中一项就是时区的设置。php.ini里增加了对应的设置date.timezone,同时也增加了相 应的函数date_default_timezone_get()和date-default_timezone_set()。如果不设置且未在程序中指 定,可能会在使用date/time函数时产生时差问题(win32平台就是)。
date_default_timezone_get()对时区的判定按照以下顺序:
  • 使用date_default_timezone_set() 函数所设置的值(如果有)

  • TZ 环境变量(如果非空)

  • php.ini中的date.timezone 选项(如果设置过)

  • "magical" 推测(如果操作系统支持)

  • 如果以上选项没有一个成功,则返回UTC

php.ini的选项如下:
[Date]
; Defines the default timezone used by the date functions
date.timezone = Asia/Shanghai
中国可以定义为Asia/Shanghai
或者使用date_default_timezone_set()函数
bool date_default_timezone_set ( string timezone_identifier )
timezone_identifier可以参看PHP文档的Appendix H, List of Supported Timezones。php.ini中的设置也使用这些值。