Enterprise Caching Summary[using asp.net]

Original page url is:http://www.cnblogs.com/teddyma/archive/2010/02/23/1672295.html ,Author is Teddy.
let’s read the file…
Background

Caching is an very important topic in enterprise-level multi-tier application, especially for web application. A general rule for applying caching is you should consider do necessary caching at each tier of your application if possible. The other basic rule for applying caching is the closer the cache is near the user, the cheaper the cost to implement it is. For example, to implement browser side caching is much cheaper than at server side.

For a B/S application, from client to server side, possible tiers to implement caching include:

* Browser: local sandbox cache, memory cache
* Network Router: CDN
* Web Server: HTTP output cache, memory cache, distributed cache
* Application Server: memory cache, distributed cache
* Database Server: memory cache, file system cache

The Cache-Control HTTP Headers‎ standardizes the cache policy from browser, to network router and to Web server. Different Web browsers implement their internal caching according to the standard Web protocols.

CDN helps us cache and distribute content through Network routers between browsers and Web servers automatically.

Modern database systems could manage the caching of database server well enough by themselves.

So the only places need additional implementation for caching are in our application code, for a B/S application it may include:

* Browser side code (scripts, Flash/Silverlight, Java Applet/MS ActiveX/Smart Client, etc)
* Application code
* Database query code

I don’t want to talk much about caching in browser side code and database query code, because browser side caching more means how many memory you want the browser to occupy at client machine and there are no “thread synchronization” problems to be considered; and database side caching has its own guideline according to the database query language standards and different database system implementation.

So what left, worth to be discussed more is the caching in main application code. For a .NET C# application, this should mean the C# code to be compiled into executables to be deployed onto different tier servers. To be simple for discussion, let’s make our discussion below focus on .NET C# application only.
Caching in Application Code
1. Output Cache

The word “output cache” seems be invented by Microsoft together with ASP.NET. But its principle is simple. It caches the entire HTTP response message by a key which consists of a specified set of fields in a HTTP request. Since with output cache, a HTTP request could get the response message without further execution if the key exists in the output cache active key list, the performance of the Web server could be improved a lot. Especially, from II6, page level output cache could be dealt at IIS instead of at the ASP.NET ISAPI, there for, the performance is even much better than before.

So, as a general rule, for any request, if the response is possible to be reused to some extent, you should consider use output cache. But before use it, according to the “the closer the cheaper” rule, you should consider apply caching at “closer” places than Web server first. For example, practically, if possible, pay for CDN to extend the benefit of output cache out of your Web server to 3rd party CDN servers.
2. ASP.NET Cache Class and EntLib Caching Application Block

Behind the output cache, is the caching for application data. ASP.NET provides the Caching class, and similarly, the EntLib provides the caching application block. Each of the Cache class implements not only a thread safe hash table, but also common cache expiration policies. But so far, there are still not build-in cache replacement algorithms, such as FIFO & LRU, which are required by most real enterprise application. That’s why I implements a set of cache classes with LRU algorithms in NIntegrate. And either of the Cache classes is still in-process caching only, which means, in a load-balanced farm, the application data cached in Cache instances may exists duplicated in each of the server in the farm.
3. Caching Service & Distributed Hash Table

If you want to shared cached data among processes and even among servers, you need shared caching service in separate process or distributed hash table.

A caching service is a service wrapping a hash table executing in a separate process, but store shared data among different processes on the same server. For example, I could implement it as a namedpipe binding based WCF service, exposing methods for operating an internal hash table, which stores shared application data of 3 ASP.NET application deployed on the same Web server.

Furthermore, a distributed hash table is more like a caching service be deployed on a separate server or even farm, which stores shared application data of different applications deployed on different servers and farms. The biggest benefit of distributed hash table is the cached data is not duplicated in different server, so you could expire cached data centrally. But you should realize that the performance of a distributed hash table is worse than a caching service deployed on the same server of an application, and of course far worse than in-process caching. But in practice, because in most cases, the performance bottle neck of enterprise applications is database server, and compare to querying database, the performance of distributed hash table is still much faster and it could be scale-out easier than database, so distributed hash table could still benefit a lot on performance and is a indispensable part of enterprise applications.
–the end –
Yes ,you know the caching must be using three types on ouput or application or database ,so you can optimize it with these types on php.if use outpucache ,you can choose ob_* function.if use application cache,you can choose APC or Eacceraltor or ZendOptimizer.If use database cache ,you can choose memcached or filecache .

Using Bloom Filters

前段时间,yhustc问群里的人说是,如果有两个4G的文件,怎么样把其中相同的URL取出来?(文件大小4G,每行一个URL,每个URL64个字节),一下子迷惘了。后来他说了这个Bloom Filters,于是找了点资料 。
以下为部分资料,下次贴带图片(公式)的。。【文中有图片,但事实上原文并没有图片,来源于http://www.chinaunix.net/jh/25/601028.html】
仙子注:这篇文章是半年前翻译的,最早贴于公司内部的BBS上,并引起一些争论。Bloom Filters是一种效率较高的内存索引算法,它本身具有矛盾性:一方面能快速测试目标成员是否存在,另一方面又不可避免的具有假命中率。如下文档仅供参考。
由于不知道如何在这里粘贴图片,因此本文中没有包含图片说明,请对照原文档来阅读,原文档在:http://www.perl.com/pub/a/2004/04/08/bloom_filters.html?page=1 或可email给我索取中文PDF文档。

使用Bloom Filters

原作者:Maciej Ceglowski
April 08, 2004

任何perl使用者都熟悉hash查询,一个存在测试的语句可以这样写:

foreach my $e ( @things ) { $lookup{$e}++ }

sub check {
my ( $key ) = @_;
print "Found $key!" if exists( $lookup{ $key } );
}

虽然hash查询很有用,但对非常大的列表,或keys自身非常大时,这种查询可能变得不实用。当查询hash增长得太大,通常的做法是将它移到数据库或文件中,只在本地缓存里保存最常用的关键字,这样能改善性能。

许多人不知道有一种优雅的算法,用以代替hash查询。它是一种古老的算法,叫做Bloom filter。 Bloom filter允许你在有限的内存里(你想在这块内存里存放关键字的完整列表),执行成员测试,这样就能避开使用磁盘或数据库进行查询的性能瓶颈。也许你会认为,空间的节省是有代价的:存在着可大可小的假命中率风险,并且一旦你增加key到filter后,就不能删除它。然而在许多情形下,这些局限是可接受的,bloom filter能编制有用工具。(仙子注:例如代理服务器软件Squid就使用了bloom filter算法。)

例如,假如你运行了一个高流量的在线音乐存储站点,并且如果你已知歌曲存在,就可以通过仅获取歌曲信息的方法,来最大程度的减少数据库压力。你可以在启动时构建一个bloom filter,在试图执行昂贵的数据库查询前,可以用它执行快速的成员存在测试。

use Bloom::Filter;

my $filter = Bloom::Filter->new( error_rate => 0.01, capacity => $SONG_COUNT );
open my $fh, "enormous_list_of_titles.txt" or die "Failed to open: $!";

while (< $fh>) {
chomp;
$filter->add( $_ );
}

sub lookup_song {
my ( $title ) = @_;
return unless $filter->check( $title );
return expensive_db_query( $title ) or undef;
}

在该示例里,该测试给出假命中的几率是1%,在假命中率情况下程序会执行昂贵的数据库索取操作,并最终返回空结果。尽管如此,你已避开了99%的昂贵查询时间,仅使用了用于hash查询的一小片内存。更进一步,1%假命中率的filter,每个key的存储空间在2字节以下。这比你执行完整的 hash查询所需的内存少得多。

bloom filters在Burton Bloom之后命名,Burton Bloom 1970年首先在文档里描述了它们,文档名 Space/time trade-offs in hash coding with allowable errors.在那些内存稀少的日子里,bloom filters因其简洁而倍受重视。事实上,最早的应用之一是拼写检查程序。然而,由于有少数非常明显的特性,该算法特别适合社会软件应用。

因为bloom filters使用单向hash来存储数据,因此不可能在不做穷举搜索的情况下,重建filter里的keys列表。甚至这点看起来并非象很有用,既然来自穷举搜索的假命中会覆盖掉真正的keys列表。所以bloom filters能在不向全世界广播完整列表的情况下,共享关于已有资料的信息。因为这个理由,它们在peer-to-peer应用中特别有用,在这个应用中大小和隐私是重要的约束。

bloom filters如何工作

bloom filter由2部分组成:1套k hash函数,1个给定长度的位向量。选择位向量的长度,和hash函数的数量,依赖于我们想增加多少keys到设置中,以及我们能容忍的多高的假命中率。

bloom filter中所有的hash函数被配置过,其范围匹配位向量的长度。例如,假如向量是200位长,hash函数返回的值就在1到 200之间。在filter里使用高质量的hash函数相当重要,它保证输出等分在所有可能值上--hash函数里的“热点”会增加假命中率。(仙子注:所谓“热点”是指结果过分频繁的分布在某些值上。)

要将某个key输入bloom filer中,我们在每个k hash函数里遍历它,并将结果作为在位向量里的offsets,并打开我们在该offsets上找到的任何位。假如该位已经设置,我们继续保留其打开。还没有在bloom filter里关闭位的机制。

在本示例里,让我们看看某个bloom filter,它有3个hash函数,并且位向量的长度是14。我们用空格和星号来表示位向量,以便于观察。你也许想到,空的bloom filter以所有的位关闭为开始,如图1所示。

图1:空的bloom filter

现在我们将字符apples增加到filter中去。为了做到这点,我们以apples为参数来运行每个hash函数,并采集输出:

hash1(“apples”) = 3
hash2(“apples”) = 12
hash3(“apples”) = 11

然后我们打开在向量里相应位置的位--在这里就是位3,11,和12,如图2所示。

图2:激活了3位的bloom filter

为了增加另1个key,例如plums,我们重复hash运算过程:

hash1(“plums”) = 11
hash2(“plums”) = 1
hash3(“plums”) = 8

再次打开向量里相应的位,如图3里的高亮度显示。

图3:增加了第2个key的bloom filter

注意位置11的位已被打开--在前面的步骤里,当我们增加apples时已设置了它。位11现在有双重义务,存储apples和plums两者的信息。当增加更多的keys时,它也会存储其他keys的信息。这种交迭让bloom filters如此紧凑--任何位同时编码多个keys。这种交迭也意味着你永不能从filter里取出key,因为你不能保证你所关闭的位没有携载其他keys的信息。假如我们试图执行反运算过程来从filter里删除apples,就会不经意的关闭编码plums的1个位。从bloom filter里剥离key的唯一方法是重建filter,剔除无用key。

检查是否某个key已经存在于filter的过程,非常类似于增加新key。我们在所有的hash函数里遍历key,然后检查是否在那些 offsets上的位都是打开的。假如任何一位关闭,我们知道该key肯定不存在于filter中。假如所有位都打开,我们知道该key可能存在。

我说“可能”是因为存在一种情况,该key是个假命中。例如,假如我们用字符mango来测试filter,看看会发生什么情况。我们运行mango遍历hash函数:

hash1(“mango”) = 8
hash2(“mango”) = 3
hash3(“mango”) = 12

然后检查在那些offsets上的位,如图4所示。

图4:bloom filter的假命中

所有在位置3,8,和12的位都是打开的,故filter会报告mango是有效key。

当然,mango并非有效key--我们构建的filter仅包含apples和plums。事实是mango的offsets非常巧合的指向了已激活的位。这就找到了1个假命中--某个key看起来位于filter中,但实际不是。

正如你想的一样,假命中率依赖于位向量的长度和存储在filter里的keys的数量。位向量越宽阔,我们检查的所有k位被打开的可能性越小,除非该key确实存在于filter中。在hash函数的数量和假命中率之间的关系更敏感。假如使用的hash函数太少,在keys之间的差别就很少;但假如使用hash函数太多,filter会过于密集,增加了冲突的可能性。可以使用如下公式来计算任何filter的假命中率:

c = ( 1 – e(-kn/m) )k

这里c是假命中率,k是hash函数的数量,n是filter里keys的数量,m是filter的位长。

当使用bloom filters时,我们先要有个意识,期待假命中率多大;也应该有个粗糙的想法,关于多少keys要增加到filter里。我们需要一些方法来验证需要多大的位向量,以保证假命中率不会超出我们的限制。下列方程式会从错误率和keys数量求出向量长度:

m = -kn / ( ln( 1 – c ^ 1/k ) )

请注意另1个自由变量:k,hash函数的数量。可以用微积分来得出k的最小值,但有个偷懒的方法来做它:

sub calculate_shortest_filter_length {
my ( $num_keys, $error_rate ) = @_;
my $lowest_m;
my $best_k = 1;

foreach my $k ( 1..100 ) {
my $m = (-1 * $k * $num_keys) /
( log( 1 - ($error_rate ** (1/$k))));

if ( !defined $lowest_m or ($m < $lowest_m) ) {
$lowest_m = $m;
$best_k   = $k;
}
}
return ( $lowest_m, $best_k );
}

为了给你直观的感觉,关于错误率和keys数量如何影响bloom filters的存储size,表1列出了一些在不同的容量/错误率组合下的向量size。

ErrorRate Keys RequiredSize Bytes/Key
1% 1K 1.87 K 1.9
0.1% 1K 2.80 K 2.9
0.01% 1K 3.74 K 3.7
0.01% 10K 37.4 K 3.7
0.01% 100K 374 K 3.7
0.01% 1M 3.74 M 3.7
0.001% 1M 4.68 M 4.7
0.0001% 1M 5.61 M 5.7

在Perl里构建bloom filter

为了构建1个工作bloom filter,我们需要1套良好的hash函数。这些容易解决--在CPAN上有几个优秀的hash算法可用。对我们的目的来说,较好的选择是Digest::SHA1,它是强度加密的hash,用C实现速度很快。通过对不同值的输出列表进行排序,我们能使用该模块来创建任意数量的hash函数。如下是构建唯一hash函数列表的子函数:

use Digest::SHA1 qw/sha1/;

sub make_hashing_functions {
my ( $count ) = @_;
my @functions;

for my $salt (1..$count ) {
push @functions, sub { sha1( $salt, $_[0] ) };
}

return @functions;
}

为了能够使用这些hash函数,我们必须找到1个方法来控制其范围。Digest::SHA1返回令人为难的过长160位hash输出,这仅在向量长度为2的160次方时有用,而这种情况实在罕见。我们结合使用位chopping和division来将输出削减到可用大小。

如下子函数取某个key,运行它遍历hash函数列表,并返回1个长度($FILTER_LENGTH)的位掩码:

sub make_bitmask {
my ( $key ) = @_;
my $mask    = pack( "b*", '0' x $FILTER_LENGTH);

foreach my $hash_function ( @functions ){ 

my $hash       = $hash_function->($key);
my $chopped    = unpack("N", $hash );
my $bit_offset = $result % $FILTER_LENGTH;

vec( $mask, $bit_offset, 1 ) = 1;
}
return $mask;
}

让我们逐行分析上述代码:

my $mask = pack( "b*", '0' x $FILTER_LENGTH);

我们以使用perl的pack操作来创建零位向量开始,它是$FILTER_LENGTH长。pack取2个参数,1个模型和1个值。b模型告诉 pack将值解释为bits,*指“重复任意多需要的次数”,跟正则表达式类似。perl实际上会补充位向量的长度为8的倍数,但我们将忽视这些多余位。

有1个空的位向量在手中,我们准备开始运行key遍历hash函数:

my $hash = $hash_function->($key);
my $chopped = unpack("N", $hash );

我们保存首个32位输出,并丢弃剩下的。这点可让我们不必要求BigInt支持。第2行做实际的位chopping。模型里的N告诉unpack以网络字节顺序来解包32位整数。因为未在模型里提供任何量词,unpack仅解包1个整数,然后终止。

假如你对位chopping过度狂热,你可以将hash分割成5个32位的片断,并对它们一起执行OR运算,将所有信息保存在原始hash里:

my $chopped = pack( "N", 0 );
my @pieces  =  map { pack( "N", $_ ) } unpack("N*", $hash );
$chopped    = $_ ^ $chopped foreach @pieces;

但这样作可能杀伤力过度。

现在我们有了来自hash函数的32位整数输出的列表,下一步必须做的是,裁减它们的大小,以使其位于(1..$FILTER_LENGTH)范围内。

my $bit_offset = $chopped % $FILTER_LENGTH;

现在我们已转换key为位offsets列表,这正是我们所求的。

剩下唯一要做的事情是,使用vec来设置位,vec取3个参数:向量自身,开始位置,要设置的位数量。我们能象赋值给变量一样来分配值给vec:

vec( $mask, $bit_offset, 1 ) = 1;

在设置了所有位后,我们以1个位掩码来结束,位掩码和bloom filter长度一样。我们可以使用这个掩码来增加key到filter中:

sub add {
my ( $key, $filter ) = @_;

my $mask = make_bitmask( $key );
$filter  = $filter | $mask;
}

或者我们使用它来检查是否key已存在:

sub check {
my ( $key, $filter ) = @_;
my $mask  = make_bitmask( $key );
my $found = ( ( $filter & $mask ) eq $mask );
return $found;
}

注意这些是位逻辑运算符OR(|)和AND(&),而并非通用的逻辑OR(||)和AND(&&)运算符。将这两者混在一起,会导致数小时的有趣调试。第1个示例将掩码和位向量进行OR运算,打开任何未设置的位。第2个示例将掩码和filter里相应的位置进行比较--假如掩码里所有的打开位也在filter里打开,我们知道已找到一个匹配。

一旦你克服了使用vec,pack和位逻辑运算符的难度,bloom filters实际非常简单。http://www.perl.com/2004/04/08/examples/Filter.pm 这里给出了Bloom::Filter模块的完整信息。

分布式社会网络中的bloom filters

当前的社会网络机制的弊端之一是,它们要求参与者泄露其联系列表给中央服务器,或公布它到公共Internet,这2种情况下都牺牲了大量的用户隐私。通过交换bloom filters而不是暴露联系列表,用户能参与社会网络实践,而不用通知全世界他们的朋友是谁。编码了某人联系信息的 bloom filter能用来检查它是否包含了给定的用户名或email地址,但不能强迫要求它展示用于构建它的完整keys列表。甚至有可能将假命中率(虽然它听起来不像好特性),转换为有用工具。

假如我非常关注这些人,他们通过对bloom filter运行字典攻击,来试图对社会网络进行反工程。我可以构建filter,它具备较高的假命中率(例如50%),然后发送filter的多个拷贝给朋友,并变换用于构建每个filter的hash函数。我的朋友收集到的filters越多,他们见到的假命中率越低。例如,在5个filters情况下,假命中率是0.5的5次方,或3%--通过发送更多filters,还能进一步减少假命中率。

假如这些filters中的任何一个被中途截取,它会展示全部50%的假命中率。所以我能隔离隐私风险,并且一定程度上能控制其他人能多清楚的

了解我的网络。我的朋友能较高程度的确认是否某个人位于联系列表里,但那些仅截取了1个或2个filters的人,几乎不会获取到什么。如下是个perl函数,它对1组嘈杂的filters检查某个key:

use Bloom::Filter;

sub check_noisy_filters {
my ( $key, @filters ) = @_;
foreach my $filter ( @filters ) {
return 0 unless $filter->check( $key );
}
return 1;
}

假如你和你的朋友同意使用相同的filter长度和hash函数设置,你也能使用位掩码对比来估计在你们的社会网络之间的交迭程度。在2个bloom filters里的共享位数量会给出1个可用的距离度量。

sub shared_on_bits {
my ( $filter_1, $filter_2 ) = @_;
return unpack( "%32b*",  $filter_1 & $filter_2 )
}

另外,你能使用OR运算,结合2个有相同长度和hash函数的bloom filters来创建1个复合filter。例如,假如你参与某个小型邮件列表,并希望基于组里每个人的地址本来创建白名单,你可以为每个参与者独立的创建1个bloom filter,然后将filters一起进行OR运算,将结果输入Voltron-like主列表。组里成员不会了解到其他成员的联系信息,并且filter仍能展示正确的行为。

肯定还有其他针对社会网络和分布式应用的bloom filter妙用。如下参考列出一些有用资源。

参考
· Bloom Filters — the math. A good place to start for an overview of the math behind Bloom filters.
· Some Motley Bloom Tricks. Handy filter tricks and theory page.
· Bloom Filter Survey. A handy survey article on Bloom filter network applications.
· LOAF. Our own system for incorporating social networks onto email using Bloom filters.
· Compressed Bloom Filters. If you are passing filters around a network, you will want to optimize them for minimum size; this paper gives a good overview of compressed Bloom filters.
· Bloom16. A CPAN module implementing a counting Bloom filter.
· Text::Bloom. CPAN module for using Bloom filters with text collections.
· Privacy-Enhanced Searches Using Encryted Bloom Filters. This paper discusses how to use encryption and Bloom filters to set up a query system that prevents the search engine from knowing the query you are running.
· Bloom Filters as Summaries. Some performance data on actually using Bloom filters as cache summaries.
· Using Bloom Filters for Authenticated Yes/No Answers in the DNS. Internet draft for using Bloom filters to implement Secure DNS

Yii framework documentation and api manual

When you wrote your php code with yii framewok,you must look the reference.so i try to find yii framework documentation and api manual.
Yii api manual is a chm file,so you can download it ,and you can write code for the reference.(又在乱写了。。。)
Yii documentation that gives the definitive description of every feature of Yii and is being constantly updated to reflect the latest enhancements and changes.it’s showed on Yii frontpage.This tutorial release also available by some languages.Chinese also among them.
if you want to find chinese manual ,please type the url:

http://www.yiiframework.com/doc/guide/zh_cn/index

and

http://dreamneverfall.cn/yiidoc/index.htm.

And you can also be downloaded in PDF format.
Over…

php-curl manual

curl 是使用URL语法的传送文件工具,支持FTP、FTPS、HTTP HTPPS SCP SFTP TFTP TELNET DICT FILE和LDAP。curl 支持SSL证书、HTTP POST、HTTP PUT 、FTP 上传,kerberos、基于HTT格式的上传、代理、cookie、用户+口令证明、文件传送恢复、http代理通道和大量其他有用的技巧。详见参考手册。

以下关于此函数各项使用参数:

bool curl_setopt (int ch, string option, mixed value)

curl_setopt()函数将为一个CURL会话设置选项。option参数是你想要的设置,value是这个选项给定的值。

下列选项的值将被作为长整形使用(在option参数中指定):

* CURLOPT_INFILESIZE: 当你上传一个文件到远程站点,这个选项告诉PHP你上传文件的大小。
* CURLOPT_VERBOSE: 如果你想CURL报告每一件意外的事情,设置这个选项为一个非零值。
* CURLOPT_HEADER: 如果你想把一个头包含在输出中,设置这个选项为一个非零值。
* CURLOPT_NOPROGRESS: 如果你不会PHP为CURL传输显示一个进程条,设置这个选项为一个非零值。注意:PHP自动设置这个选项为非零值,你应该仅仅为了调试的目的来改变这个选项。
* CURLOPT_NOBODY: 如果你不想在输出中包含body部分,设置这个选项为一个非零值。
* CURLOPT_FAILONERROR: 如果你想让PHP在发生错误(HTTP代码返回大于等于300)时,不显示,设置这个选项为一人非零值。默认行为是返回一个正常页,忽略代码。
* CURLOPT_UPLOAD: 如果你想让PHP为上传做准备,设置这个选项为一个非零值。
* CURLOPT_POST: 如果你想PHP去做一个正规的HTTP POST,设置这个选项为一个非零值。这个POST是普通的 application/x-www-from-urlencoded 类型,多数被HTML表单使用。
* CURLOPT_FTPLISTONLY: 设置这个选项为非零值,PHP将列出FTP的目录名列表。
* CURLOPT_FTPAPPEND: 设置这个选项为一个非零值,PHP将应用远程文件代替覆盖它。
* CURLOPT_NETRC: 设置这个选项为一个非零值,PHP将在你的 ~./netrc 文件中查找你要建立连接的远程站点的用户名及密码。
* CURLOPT_FOLLOWLOCATION: 设置这个选项为一个非零值(象 “Location: “)的头,服务器会把它当做HTTP头的一部分发送(注意这是递归的,PHP将发送形如 “Location: “的头)。
* CURLOPT_PUT: 设置这个选项为一个非零值去用HTTP上传一个文件。要上传这个文件必须设置CURLOPT_INFILE和CURLOPT_INFILESIZE选项.
* CURLOPT_MUTE: 设置这个选项为一个非零值,PHP对于CURL函数将完全沉默。
* CURLOPT_TIMEOUT: 设置一个长整形数,作为最大延续多少秒。
* CURLOPT_LOW_SPEED_LIMIT: 设置一个长整形数,控制传送多少字节。
* CURLOPT_LOW_SPEED_TIME: 设置一个长整形数,控制多少秒传送CURLOPT_LOW_SPEED_LIMIT规定的字节数。
* CURLOPT_RESUME_FROM: 传递一个包含字节偏移地址的长整形参数,(你想转移到的开始表单)。
* CURLOPT_SSLVERSION: 传递一个包含SSL版本的长参数。默认PHP将被它自己努力的确定,在更多的安全中你必须手工设置。
* CURLOPT_TIMECONDITION: 传递一个长参数,指定怎么处理CURLOPT_TIMEVALUE参数。你可以设置这个参数为TIMECOND_IFMODSINCE 或 TIMECOND_ISUNMODSINCE。这仅用于HTTP。
* CURLOPT_TIMEVALUE: 传递一个从1970-1-1开始到现在的秒数。这个时间将被CURLOPT_TIMEVALUE选项作为指定值使用,或被默认 TIMECOND_IFMODSINCE使用。

下列选项的值将被作为字符串:

* CURLOPT_URL: 这是你想用PHP取回的URL地址。你也可以在用curl_init()函数初始化时设置这个选项。
* CURLOPT_USERPWD: 传递一个形如[username]:[password]风格的字符串,作用PHP去连接。
* CURLOPT_PROXYUSERPWD: 传递一个形如[username]:[password] 格式的字符串去连接HTTP代理。
* CURLOPT_RANGE: 传递一个你想指定的范围。它应该是”X-Y”格式,X或Y是被除外的。HTTP传送同样支持几个间隔,用逗句来分隔(X-Y,N-M)。
* CURLOPT_POSTFIELDS: 传递一个作为HTTP “POST”操作的所有数据的字符串。
* CURLOPT_REFERER: 在HTTP请求中包含一个”referer”头的字符串。
* CURLOPT_USERAGENT: 在HTTP请求中包含一个”user-agent”头的字符串。
* CURLOPT_FTPPORT: 传递一个包含被ftp “POST”指令使用的IP地址。这个POST指令告诉远程服务器去连接我们指定的IP地址。这个字符串可以是一个IP地址,一个主机名,一个网络界面名 (在UNIX下),或是‘-’(使用系统默认IP地址)。
* CURLOPT_COOKIE: 传递一个包含HTTP cookie的头连接。
* CURLOPT_SSLCERT: 传递一个包含PEM格式证书的字符串。
* CURLOPT_SSLCERTPASSWD: 传递一个包含使用CURLOPT_SSLCERT证书必需的密码。
* CURLOPT_COOKIEFILE: 传递一个包含cookie数据的文件的名字的字符串。这个cookie文件可以是Netscape格式,或是堆存在文件中的HTTP风格的头。
* CURLOPT_CUSTOMREQUEST: 当进行HTTP请求时,传递一个字符被GET或HEAD使用。为进行DELETE或其它操作是有益的,更Pass a string to be used instead of GET or HEAD when doing an HTTP request. This is useful for doing or another, more obscure, HTTP request. 注意: 在确认你的服务器支持命令先不要去这样做。下列的选项要求一个文件描述(通过使用fopen()函数获得):
* CURLOPT_FILE: 这个文件将是你放置传送的输出文件,默认是STDOUT.
* CURLOPT_INFILE: 这个文件是你传送过来的输入文件。
* CURLOPT_WRITEHEADER: 这个文件写有你输出的头部分。
* CURLOPT_STDERR: 这个文件写有错误而不是stderr。用来获取需要登录的页面的例子,当前做法是每次或许都登录一次,有需要的人再做改进了.

If you want to look ennglish manual,you can find it from “http://cn.php.net/manual/en/curl.constants.php”,and example page is:http://www.neatcn.com/show-23-1.shtml.
The Chinese manual from php-curl ,copy from http://52037872.cn/blog/post/263

try to use Yii framework

i want to try use the framework named Yii,so i downloaded it .
It’s so easy to create a new project.
First,please edit yiic.bat on framework directory,and set PHP_COMMAND path.
Second.open yiic.bat on command line.if no paramters ,it will be show:

Yii command runner (based on Yii v1.1.1)
Usage: E:\www\htdocs\travel\yii\framework\yiic [parameters...]

The following commands are available:
– message
– shell
– webapp

To see individual command help, use the following:
E:\www\htdocs\travel\yii\framework\yiic help

Third.type yiic.bat webapp test,and type yes,yiic.bat created the project by name test.
//以后要学英文,越写越烂。
//请不要指责英文,本身就很烂,语法错误非常多,看得懂就行吧,当然能够告诉我语法错误也好,以后逐步改善吧,毕竟不写,永远也写不对。

array search

其实这是并不能算是一个search的方法,但我写这个方法是为了快速定位到数组里的key,以返回相应的值。

例如:

$arr = array(
    'a' => array(
        'b' => array(
            'c' => array(
                'd'
            )
        )
    ),
    'e' => array(
        'f' => array(
            'g' => array(
                'h'
            ),
            'i' => array(
                'j'
            )
        )
    )
);

象这样的数组,如果要取$arr['a']['b']['c']这样的值,写起来有点复杂,于是我这样写了一个函数

function search( $keys , $arr ){
    if(!is_array($arr) && !is_object($arr)){
        return ;
    }
    $keys = explode("." , $keys );
    $_err = false;
    foreach($keys as $key){
        if(isset($arr[$key])){
            $arr = $arr[$key];
        }else{
            $_err = true;
            break;
        }
    }
    if($_err == true)return ;
    return $arr;
}

这样就很好办了。。直接$e = search(“a.b.c” , $arr);
就可以返回值了

根据日期取得当前的星期

PHP的date函数是有时间范围区间的,即只能从1970~2038年,因此在这个区间范围之外的算法都是不准的。那倒底怎么算呢?其实是有一个公式的:

蔡勒(Zeller)公式:w=y+[y/4]+[c/4]-2c+[26(m+1)/10]+d-1

公 式中的符号含义如下,w:星期;c:世纪-1;y:年(两位数);m:月(m大于等于3,小于等于14,即在蔡勒公式中,某年的1、2月要看作上一年的 13、14月来计算,比如2003年1月1日要看作2002年的13月1日来计算);d:日;[ ]代表取整,即只要整数部分。(C是世纪数减一,y是年份后两位,M是月份,d是日数。1月和2月要按上一年的13月和 14月来算,这时C和y均按上一年取值。)

算出来的W除以7,余数是几就是星期几。如果余数是0,则为星期日。【膘叔备注,如果小于0,则先+7再取余数

以2049年10月1日(100周年国庆)为例,用蔡勒(Zeller)公式进行计算,过程如下:
蔡勒(Zeller)公式:w=y+[y/4]+[c/4]-2c+[26(m+1)/10]+d-1
=49+[49/4]+[20/4]-2×20+[26× (10+1)/10]+1-1
=49+[12.25]+5-40+[28.6]
=49+12+5-40+28
=54 (除以7余5)
即2049年10月1日(100周年国庆)是星期5。

你的生日(出生时、今年、明年)是星期几?不妨试一试。
但其实上面的并不是特别准,我根据上面的公式写了一段代码。。。

//蔡勒(Zeller)公式:w=y+[y/4]+[c/4]-2c+[26(m+1)/10]+d-1
function getDayofWeek ( $datetime , $delimiter = '-' )
{
        //其实这个explode,可以参考split函数,它的分隔支持类似正则的批量处理,比如split("[/.-]",$datetime),可以查一下手册
	list($year,$month,$day) = explode( $delimiter, $datetime );
	if(strLen( $year ) == 2 && $year < 50){
		$century = 20;	//世纪数为当前世纪数-1
	}else{
		$century = subStr( $year, 0,2 ) ;
		$year = subStr( $year, -2 );
	}
	$week = ( $year + floor($year/4) + floor($century / 4) - 2*$century + floor( 26*($month+1)/10)+$day-1 ) % 7; //floor($year/4),代表不取小数点后的值,即,不四舍五入
	return ($week + 7 ) % 7;	//如果有负数出现,则转为正数再取模,就是正常的星期了。
}

echo( getDayofWeek( '1999-05-02') );

上面部分文字来自于http://www.neatstudio.com/show-1174-1.shtml

为Zend的table加上prefix

我不知道别人是怎么做的。我做的很累啊。。。明明在继承Zend_Db_Table_Abstract的类中打印getAdapter方法时,有_config变量,但是,它是protected的,没有找到合适的方法调用。
于是没办法。到bootstrap.php文件里加了一个方法。

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected $_bootConfig;

    public function  __construct( $application ) {
        parent::__construct($application);
        $this->_bootConfig = new Zend_Config_Ini( APPLICATION_PATH . '/configs/application.ini' );
        Zend_Registry::set('config', $this->_bootConfig);
    }
}

这样。我在bootstrap中也能直接使用 $this->_bootConfig 的变量。因为我使用了smarty,而且用的不是继承的方法。所以直接在__construct方法中把config变量赋值出来也有一定的方便之处。
就象这样:

    public function _initView()
    {
        require_once ('Smarty/Smarty.class.php');
        $tpl = new Smarty();
        $tplSettings = $this->_bootConfig->staging->smarty->toArray();
        foreach( $tplSettings as $key=>$value){
            $tpl->$key = $value;
        }
        Zend_Registry::set( 'tpl', $tpl);
    }

这样 _initView 之后,一定要在 application.ini里设置
resources.frontController.noViewRenderer = 1
不过这样就没有办法用zend_view的layout 。。。
于是我现在就在Zend_Db_Table_Abstract的继承类里用 init方法加了简单的处理

    public function init(){
        $config = Zend_Registry::get('config')->toArray();
        if(isset( $config['production']['resources']['db']['params']['prefix'] )){
            $prefix = strval( $config['production']['resources']['db']['params']['prefix'] );
            $this->_name =  $prefix . $this->_name ;
        }
    }

Over。解决。。。。

简单学习一下Zend_ACL

如果不想用rbac那么,简单权限管理ACL,应该是最方便的了。简要说一下原理吧。。
这个文件是放在/application/models/目录下的Acl.php,调用的时候就直接

$identity = Zend_Auth::getInstance()->getIdentity();
$acl = new Application_Model_Acl();
//然后判断
if( $acl->isAllowed( $identity['Role'] , 'xxxxx' ,'yyyy' )); //xxxx是controller名,yyyy是controller里的action名称。不用额外加action。。。
class Application_Model_Acl extends Zend_Acl
{

	public function __construct()
	{
		/*
		 *  第一次添加权限 "guest" ,支持查看所有的内容
		 */
		$this->addRole(new Zend_Acl_Role('guest'));

		/*
		 * 添加 'user' 组权限,权限大于 guest
		 * 用户组能够发表回复
		 */
		$this->addRole(new Zend_Acl_Role('user'), 'guest');

		/*
		 * 添加一个auth组
		 * auth用户权限基于user,并且可以发表文章
		 */
		$this->addRole(new Zend_Acl_Role('auth'), 'user');

		/*
		 * 添加admin组权限,可以做任何事情
		 */
		$this->addRole(new Zend_Acl_Role('admin'), 'blogger');

		//添加允许使用的Resource(也就是controller名啦),这是posts controller
		$this->add(new Zend_Acl_Resource('posts'));

		//添加允许使用的Resource(也就是controller名啦),这是comments controller
		$this->add(new Zend_Acl_Resource('comments'));

		//最后,添加权限,guest用户组可以执行posts controller下的view方法
		$this->allow('guest', 'posts', 'view');

		//User组可以执行 comments controller下的Add 方法
		$this->allow('user', 'comments', 'add');

		// auth 除了上面的功能外还能够支持 posts controller 中的Edit和add方法
		$this->allow('auth', 'posts', 'edit');
		$this->allow('auth', 'posts', 'add');
	}

}

是不是很方便?ACL就是这样的方便 。。

QeePHP中的优秀函数(三)

这几个函数还是来自于QeePHP的核心类Q中。不过,我是自认为,我的configure类有部分写的比他好,不过我没有考虑删除之类的。呵呵。

    /**
     * 获取指定的设置内容
     *
     * $option 参数指定要获取的设置名。
     * 如果设置中找不到指定的选项,则返回由 $default 参数指定的值。
     *
     * @code php
     * $option_value = Q::ini('my_option');
     * @endcode
     *
     * 对于层次化的设置信息,可以通过在 $option 中使用“/”符号来指定。
     *
     * 例如有一个名为 option_group 的设置项,其中包含三个子项目。
     * 现在要查询其中的 my_option 设置项的内容。
     *
     * @code php
     * // +--- option_group
     * //   +-- my_option  = this is my_option
     * //   +-- my_option2 = this is my_option2
     * //   \-- my_option3 = this is my_option3
     *
     * // 查询 option_group 设置组里面的 my_option 项
     * // 将会显示 this is my_option
     * echo Q::ini('option_group/my_option');
     * @endcode
     *
     * 要读取更深层次的设置项,可以使用更多的“/”符号,但太多层次会导致读取速度变慢。
     *
     * 如果要获得所有设置项的内容,将 $option 参数指定为 '/' 即可:
     *
     * @code php
     * // 获取所有设置项的内容
     * $all = Q::ini('/');
     * @endcode
     *
     * @param string $option 要获取设置项的名称
     * @param mixed $default 当设置不存在时要返回的设置默认值
     *
     * @return mixed 返回设置项的值
     */
    static function ini($option, $default = null)
    {
        if ($option == '/') return self::$_ini;

        if (strpos($option, '/') === false)
        {
            return array_key_exists($option, self::$_ini)
                ? self::$_ini[$option]
                : $default;
        }

        $parts = explode('/', $option);
        $pos =& self::$_ini;
        foreach ($parts as $part)
        {
            if (!isset($pos[$part])) return $default;
            $pos =& $pos[$part];
        }
        return $pos;
    }

    /**
     * 修改指定设置的内容
     *
     * 当 $option 参数是字符串时,$option 指定了要修改的设置项。
     * $data 则是要为该设置项指定的新数据。
     *
     * @code php
     * // 修改一个设置项
     * Q::changeIni('option_group/my_option2', 'new value');
     * @endcode
     *
     * 如果 $option 是一个数组,则假定要修改多个设置项。
     * 那么 $option 则是一个由设置项名称和设置值组成的名值对,或者是一个嵌套数组。
     *
     * @code php
     * // 假设已有的设置为
     * // +--- option_1 = old value
     * // +--- option_group
     * //   +-- option1 = old value
     * //   +-- option2 = old value
     * //   \-- option3 = old value
     *
     * // 修改多个设置项
     * $arr = array(
     *      'option_1' => 'value 1',
     *      'option_2' => 'value 2',
     *      'option_group/option2' => 'new value',
     * );
     * Q::changeIni($arr);
     *
     * // 修改后
     * // +--- option_1 = value 1
     * // +--- option_2 = value 2
     * // +--- option_group
     * //   +-- option1 = old value
     * //   +-- option2 = new value
     * //   \-- option3 = old value
     * @endcode
     *
     * 上述代码展示了 Q::changeIni() 的一个重要特性:保持已有设置的层次结构。
     *
     * 因此如果要完全替换某个设置项和其子项目,应该使用 Q::replaceIni() 方法。
     *
     * @param string|array $option 要修改的设置项名称,或包含多个设置项目的数组
     * @param mixed $data 指定设置项的新值
     */
    static function changeIni($option, $data = null)
    {
        if (is_array($option))
        {
            foreach ($option as $key => $value)
            {
                self::changeIni($key, $value);
            }
            return;
        }

        if (!is_array($data))
        {
            if (strpos($option, '/') === false)
            {
                self::$_ini[$option] = $data;
                return;
            }

            $parts = explode('/', $option);
            $max = count($parts) - 1;
            $pos =& self::$_ini;
            for ($i = 0; $i < = $max; $i ++)
            {
                $part = $parts[$i];
                if ($i < $max)
                {
                    if (!isset($pos[$part]))
                    {
                        $pos[$part] = array();
                    }
                    $pos =& $pos[$part];
                }
                else
                {
                    $pos[$part] = $data;
                }
            }
        }
        else
        {
            foreach ($data as $key => $value)
            {
                self::changeIni($option . '/' . $key, $value);
            }
        }
    }

    /**
     * 替换已有的设置值
     *
     * Q::replaceIni() 表面上看和 Q::changeIni() 类似。
     * 但是 Q::replaceIni() 不会保持已有设置的层次结构,
     * 而是直接替换到指定的设置项及其子项目。
     *
     * @code php
     * // 假设已有的设置为
     * // +--- option_1 = old value
     * // +--- option_group
     * //   +-- option1 = old value
     * //   +-- option2 = old value
     * //   \-- option3 = old value
     *
     * // 替换多个设置项
     * $arr = array(
     *      'option_1' => 'value 1',
     *      'option_2' => 'value 2',
     *      'option_group/option2' => 'new value',
     * );
     * Q::replaceIni($arr);
     *
     * // 修改后
     * // +--- option_1 = value 1
     * // +--- option_2 = value 2
     * // +--- option_group
     * //   +-- option2 = new value
     * @endcode
     *
     * 从上述代码的执行结果可以看出 Q::replaceIni() 和 Q::changeIni() 的重要区别。
     *
     * 不过由于 Q::replaceIni() 速度比 Q::changeIni() 快很多,
     * 因此应该尽量使用 Q::replaceIni() 来代替 Q::changeIni()。
     *
     * @param string|array $option 要修改的设置项名称,或包含多个设置项目的数组
     * @param mixed $data 指定设置项的新值
     */
    static function replaceIni($option, $data = null)
    {
        if (is_array($option))
        {
            self::$_ini = array_merge(self::$_ini, $option);
        }
        else
        {
            self::$_ini[$option] = $data;
        }
    }

    /**
     * 删除指定的设置
     *
     * Q::cleanIni() 可以删除指定的设置项目及其子项目。
     *
     * @param mixed $option 要删除的设置项名称
     */
    static function cleanIni($option)
    {
        if (strpos($option, '/') === false)
        {
            unset(self::$_ini[$option]);
        }
        else
        {
            $parts = explode('/', $option);
            $max = count($parts) - 1;
            $pos =& self::$_ini;
            for ($i = 0; $i < = $max; $i ++)
            {
                $part = $parts[$i];
                if ($i < $max)
                {
                    if (!isset($pos[$part]))
                    {
                        $pos[$part] = array();
                    }
                    $pos =& $pos[$part];
                }
                else
                {
                    unset($pos[$part]);
                }
            }
        }
    }