手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆
浏览模式: 标准 | 列表分类:PHP

扩展yii的验证类

在项目中遇到文件上传的问题,这时候需要用到CFileValidator,但是官方的验证中少了一点点的处理,比如,对于图片,我只想上传尺寸正好是300x500的图片。怎么办?
所以我做了一点小小的扩展,于是我在rules里面加了这么两条:

PHP代码
  1. array('picname''application.validators.Myfile''on'=>'insert','types'=>'jpg,png','wrongType'=>'只允许上传jpg或者PNG','maxSize' => 1024*300,'tooLarge' => '图片最大只支持300K','imageSize'=>'768x1024','wrongImageSize'=>'对不起,图片尺寸只支持768*1024'),  
  2.          array('picname''application.validators.Myfile''on'=>'update','types'=>'jpg,png','wrongType'=>'只允许上传jpg或者PNG','maxSize' => 1024*300,'tooLarge' => '图片最大只支持300K','imageSize'=>'768x1024','wrongImageSize'=>'对不起,图片尺寸只支持768*1024','allowEmpty'=>true,),  

数组的第二个字段就是一个全路径,告诉rules,对于picname用的是application.validators.Myfile类。这个类其实很简单,只是简单的扩展了官方的CFileValidator类,大致如下:

PHP代码
  1. class Myfile extends CFileValidator{  
  2.     public $imageSize;  
  3.     public $wrongImageSize;  
  4.   
  5.     /** 
  6.      * @param CModel $object the object being validated 
  7.      * @param string $attribute the attribute being validated 
  8.      * @param CUploadedFile $file uploaded file passed to check against a set of rules 
  9.      * @return void 
  10.      */  
  11.     protected function validateFile($object$attribute$file){  
  12.         parent::validateFile($object,$attribute,$file);  
  13.         if($this->imageSize!=''&&strpos($this->imageSize,"x")!==false){  
  14.             list($width,$height) = @getimagesize($file->getTempName());  
  15.             $imageSize = sprintf("%sx%s",$width,$height);  
  16.             if($imageSize != $this->imageSize){  
  17.                 $message=$this->wrongImageSize!==null?$this->wrongImageSize : Yii::t('yii','The file "{file}" cannot be uploaded. Only files with these size are allowed: {imagesize}.');  
  18.                 $this->addError($object,$attribute,$message,array('{file}'=>$file->getName(), '{extensions}'=>$this->imageSize));  
  19.             }  
  20.         }  
  21.     }  
  22. }  

我这种只是简单的判断是否与指定尺寸相符,如果需要检测小于指定范围的图片,那就需要多一点的判断了,也不会太难啦。主要是一个思路(感谢烂桔提供思路)

Tags: yii

xml2array 和 array2xml

这是一个简单的方法,其实是两种方法的其中一种:xml2array 和 array2xml 中的一种啦。
但因为array2xml的时候,没有办法做到更好的把attributes做到更好,因此,就折腾了一些简单的处理方法:
array2xml是hightman的方法的简版。我自己改了一些:

PHP代码
  1. function array2xml($var$type = 'root'$tag = '') {  
  2.    $ret = '';  
  3.    if (!is_int($type)) {  
  4.        if ($tag)  
  5.            return array2xml(array($tag => $var), 0, $type); else {  
  6.            $tag .= $type;  
  7.            $type = 0;  
  8.        }  
  9.    }  
  10.    $level = $type;  
  11.    $indent = str_repeat("\t"$level);  
  12.    if (!is_array($var)) {  
  13.        $ret .= $indent . '<' . $tag;  
  14.        $var = strval($var);  
  15.        if ($var == '') {  
  16.            $ret .= ' />';  
  17.        } else if (!preg_match('/[^0-9a-zA-Z@\._:\/-]/'$var)) {  
  18.            $ret .= '>' . $var . '</' . $tag . '>';  
  19.        } else {  
  20.            $ret .= "><![CDATA[{$var}]]></{$tag}>";  
  21.        }  
  22.        //                if (strpos($var, "\n") === false){  
  23.        //                $ret .= '><![CDATA[' . $var . ']]></' . $tag . '>';  
  24.        //            } else  
  25.        $ret .= "\n";  
  26.    } else if (!(is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) && !emptyempty($var)) {  
  27.        foreach ($var as $tmp)  
  28.            $ret .= array2xml($tmp$level$tag);  
  29.    } else {  
  30.        $ret .= $indent . '<' . $tag;  
  31.        if ($level == 0)  
  32.            $ret .= '';  
  33.        if (isset($var['@attributes'])) {  
  34.            foreach ($var['@attributes'as $k => $v) {  
  35.                if (!is_array($v)) {  
  36.                    $ret .= sprintf(' %s="%s"'$k$v);  
  37.                }  
  38.            }  
  39.            unset($var['@attributes']);  
  40.        }  
  41.        $ret .= ">\n";  
  42.        foreach ($var as $key => $val) {  
  43.            $ret .= array2xml($val$level + 1, $key);  
  44.        }  
  45.        $ret .= "{$indent}</{$tag}>\n";  
  46.    }  
  47.    return $ret;  

在其中强加了attributes。比较恶心的方法啦。。
然后xml2array,其实以前写过,但写的不太好,所以我这次抄的是ibm的网站上的xml2json中的代码:

PHP代码
  1. define ("DEBUG", false);  
  2. // Maximum Recursion Depth that we can allow.  
  3. define ("MAX_RECURSION_DEPTH_ALLOWED", 25);  
  4. // An empty string  
  5. define ("EMPTY_STR""");  
  6. // SimpleXMLElement object property name for attributes  
  7. define ("SIMPLE_XML_ELEMENT_OBJECT_PROPERTY_FOR_ATTRIBUTES""@attributes");  
  8. // SimpleXMLElement object name.  
  9. define ("SIMPLE_XML_ELEMENT_PHP_CLASS""SimpleXMLElement");  
  10.     /** 
  11.      * @static 
  12.      * @param $simpleXmlElementObject 
  13.      * @param int $recursionDepth 
  14.      * @return array|null|string 
  15.      */  
  16.     public static function xml2array($simpleXmlElementObject$getAttributes = false , &$recursionDepth = 0 ) {  
  17.         // Keep an eye on how deeply we are involved in recursion.  
  18.         if ($recursionDepth > MAX_RECURSION_DEPTH_ALLOWED) {  
  19.             // Fatal error. Exit now.  
  20.             return (null);  
  21.         }  
  22.         if ($recursionDepth == 0) {  
  23.             if (get_class($simpleXmlElementObject) != SIMPLE_XML_ELEMENT_PHP_CLASS) {  
  24.                 // If the external caller doesn't call this function initially  
  25.                 // with a SimpleXMLElement object, return now.  
  26.                 return (null);  
  27.             } else {  
  28.                 // Store the original SimpleXmlElementObject sent by the caller.  
  29.                 // We will need it at the very end when we return from here for good.  
  30.                 $callerProvidedSimpleXmlElementObject = $simpleXmlElementObject;  
  31.             }  
  32.         } // End of if ($recursionDepth == 0) {  
  33.         if (get_class($simpleXmlElementObject) == SIMPLE_XML_ELEMENT_PHP_CLASS) {  
  34.             // Get a copy of the simpleXmlElementObject  
  35.             $copyOfsimpleXmlElementObject = $simpleXmlElementObject;  
  36.             // Get the object variables in the SimpleXmlElement object for us to iterate.  
  37.             $simpleXmlElementObject = get_object_vars($simpleXmlElementObject);  
  38.         }  
  39.         // It needs to be an array of object variables.  
  40.         if (is_array($simpleXmlElementObject)) {  
  41.             // Initialize the result array.  
  42.             $resultArray = array();  
  43.             // Is the input array size 0? Then, we reached the rare CDATA text if any.  
  44.             if (count($simpleXmlElementObject) <= 0) {  
  45.                 // Let us return the lonely CDATA. It could even be  
  46.                 // an empty element or just filled with whitespaces.  
  47.                 return (trim(strval($copyOfsimpleXmlElementObject)));  
  48.             }  
  49.             // Let us walk through the child elements now.  
  50.             foreach ($simpleXmlElementObject as $key => $value) {  
  51.                 // When this block of code is commented, XML attributes will be  
  52.                 // added to the result array.  
  53.                 // Uncomment the following block of code if XML attributes are  
  54.                 // NOT required to be returned as part of the result array.  
  55.                 /* 
  56.           if((is_string($key)) && ($key == SIMPLE_XML_ELEMENT_OBJECT_PROPERTY_FOR_ATTRIBUTES)) { 
  57.                   continue; 
  58.                 } 
  59.                 */  
  60.                 // Let us recursively process the current element we just visited.  
  61.                 // Increase the recursion depth by one.  
  62.                 $recursionDepth++;  
  63.                 if($key == '@attributes' && $getAttributes == true){  
  64.                     foreach(self::xml2array($value,$getAttributes$recursionDepthas $k=>$v){  
  65.                         $resultArray[$k]=$v;  
  66.                     }  
  67.                 }else{  
  68.                     $resultArray[$key] = self::xml2array($value,$getAttributes$recursionDepth);  
  69.                 }  
  70.                 // Decrease the recursion depth by one.  
  71.                 $recursionDepth--;  
  72.             } // End of foreach($simpleXmlElementObject as $key=>$value) {  
  73.             if ($recursionDepth == 0) {  
  74.                 // That is it. We are heading to the exit now.  
  75.                 // Set the XML root element name as the root [top-level] key of  
  76.                 // the associative array that we are going to return to the caller of this  
  77.                 // recursive function.  
  78.                 $tempArray = $resultArray;  
  79.                 $resultArray = array();  
  80.                 $resultArray[$callerProvidedSimpleXmlElementObject->getName()] = $tempArray;  
  81.             }  
  82.             return ($resultArray);  
  83.         } else {  
  84.             // We are now looking at either the XML attribute text or  
  85.             // the text between the XML tags.  
  86.             return (trim(strval($simpleXmlElementObject)));  
  87.         } // End of else  
  88.     }  

改过其中的几行代码,否则会报错,改了哪几行我忘了。。官网地址是:http://www.ibm.com/developerworks/xml/library/x-xml2jsonphp/

这里还有一个:http://www.zenme.org/?action=show&id=270,可以参考一下

Tags: xml2array

纠结,你懂的

看到这张OUTLOOK里的图,你就会懂了。为什么很多人都在问,每年的第一周到底是哪一周。。。
平时你又是怎么处理的呢?
大小: 10.59 K
尺寸: 254 x 101
浏览: 1614 次
点击打开新窗口浏览全图

Tags: 日历

step by step 学习PHP之一

这是一个比较初级的教程,应该也会一直延续下去,直到这一次教完结束
上课之前的准备
1、AMP程序,关于这一类的程序相对比较多,我这里还是推荐妖怪的apmxe,嗯,在这里有下载:apmxe备份
2、JRE ,如果你有安装360,直接到软件中心可以下载,否则到sun.com找到jre下载:http://java.com/zh_CN/download/windows_xpi.jsp?locale=zh_CN
3、netbeans ,一款用来开发PHP的IDE(事实上有很多种IDE,但我推荐它的原因是免费、跨平台),下载地址为:http://netbeans.org/downloads/start.html?platform=windows&lang=zh_CN&option=php
4、editplus 如果仅仅用来修改一两个单独的PHP文件,那么editplus应该是可选的【备用软件notepad++,理由是它免费,而editplus不免费】,editplus官网地址:http://www.editplus.com
5、PHP中文手册,开发PHP时的必备之选,下载地址:http://phpdocs-cn-chm.googlecode.com/files/php_manual_en-HonestQiao-20110507-Beta-V0.9.8.gz

OK,做完上述准备工作,让我们先一步一步的开始
1、安装apmxe,安装过程中,我们选择目标地址为d:\www,因此最终生成的路径就是d:\www\apmxe,打开这个目录会发现里面已经有很多目录了:apache22,php5,mysql5,cgi-bin,htdocs,etc,var等目录。现在我们一一介绍一下这些目录:

  1. apache22,这是apache存放的目录
  2. php5 ,自带的是PHP5.2,还不是5.3,主要因为5.3中有一些功能暂时还用不上,所以5.2也足够了
  3. mysql5 ,嗯mysql5 server,具体版本是 5.0.27,虽然有点老,但足够了
  4. cgi-bin,这个目录一般是用来处理perl的,但APMXE里并没有自带perl,因此这个目录你就当成是无效的吧(如果你有安装perl,也可以尝试着看一下目录下的文件)
  5. htdocs,WEB存放的目录,系统安装完后,已经有一些自带的程序在里面了,是QEE的一些案例,由于目前我们不是学习QEE开发,因此可以将目录下的examples和qeephp这两个目录先备份后再删除,当然phpmyadmin和xcache-admin目录还是保留着。phpmyadmin是一个可视化管理mysql的WEB程序,xcache-admin则是用来对xcache进行管理的程序。
  6. etc,apmxe程序的一些配置文件,如果你需要更改配置,修改后缀名为.template的文件,修改完后,重启apmxe,则会自动更新成最新的配置。直接修改配置文件是无效的。程序每次运行都会将.template的文件更名覆盖配置文件。
  7. var目录,很明显这是一些存放环境变量的目录,apmxe是绿色软件,因此session和tmp都不会写到系统目录里,都默认放到var目录下了。仔细看一下data目录,其实这是mysql的数据库文件,LOGs目录则是存放了WEB运行的一些日志,包括访问正常和不正常的一些日志等,用于查看WEB运行时的一些记录。

  推荐apmxe还有另外一个原因,那就是此版本的apmxe默认apache运行的端口是9000,因此访问的路径是:http://localhost:9000/ ,这有什么好处呢?它避免了下载软件和apmxe同时打开的时候,80端口的冲突(很多下载软件为了提速,都占用了80端口)
2、安装JRE,再安装netbeans。
3、安装editplus,【关于editplus可配置的东西就太多了,可以查看:http://neatstudio.com/?action=search&searchid=1118】

-----------------------------------------------------------------------------
打开netbeans,创建一个PHP的项目,项目目录指向到d:\www\apmxe\htdocs\lesson1,PHP运行环境选择为5.2,项目名称改为lesson1,点击下一步,将默认访问的URL :http://localhost/lesson1改为带端口的http://localhost:9000/lesson1,然后直接点击完成。

在IDE左侧的项目管理窗口中点击窗口前的+号,在源文件目录下点击右键,创建PHP文件,内容如下:

PHP代码
  1. <?php  
  2. echo "hello ,world";  
  3. ?>  

然后按F6,我们可以在浏览器里发现页面上输出了hello,world【说明,F6是运行项目的意思】

 

在上面的代码中我们要说明几点,<?php ,这个代表了PHP代码的开始,虽然也可以写成<?,但我们还是需要从标准出来,不要使用简写,而是需要用完整的<?php来进行表示。

既然<?php代表了开始,那么什么代表结束呢?OK,从上面的代码里我们可以看到?>,是的"?>"这个就代表了PHP代码的结束,因此我们可以认为,一段完整的PHP代码是应该包含在<?php 与 ?>之间的。

接下来我们说明一下echo "hello,world";

echo 是PHP的一个函数,它用来对浏览器中进行输出。常用的语法是echo $val; $val是一个非array或object或resource的变量(当基于这些变量时,输出的结果并非预料中的结果 )

被双引号""包含着的hello,world,是一个字符串,因此在初期我们可以认为echo 被用来输出字符串到浏览器显示。

最后,每一句PHP代码的结束标记是;,当一个PHP语句中出现了;,也就代表了该行代码的结束。

-------------------第一课先到这里,第一课我们了解了PHP运行环境以及IDE的安装,并写了一个程序员们爱用的hello world做了一个简单的测试,并在浏览器正常输出。

 下一课我们会讲解变量,常量以及赋值。如果对于上文有意见和建议,可以通过留言来反馈。谢谢

Tags: php, learn, apmxe

在Yii框架中使用Hprose或PHPRPC

Yii:

XML/HTML代码
  1. Yii is a high-performance PHP framework best for developing Web 2.0 applications.  
  2.   
  3. Yii comes with rich features: MVC, DAO/ActiveRecord, I18N/L10N, caching, authentication and role-based access control, scaffolding, testing, etc. It can reduce your development time significantly. 

PHPRPC:

XML/HTML代码
  1. PHPRPC 是一个轻型的、安全的、跨网际的、跨语言的、跨平台的、跨环境的、跨域的、支持复杂对象传输的、支持引用参数传递的、支持内容输出重定向的、支持分级错误处理的、支持会话的、面向服务的高性能远程过程调用协议。  
  2.   
  3. 目前该协议的最新版本为 3.0。该版本目前已有以下几种语言的实现:  
  4.   
  5.     ASP,ActionScript,Delphi/C++Builder/Kylix,Java,JavaScript,NET,PHP,Python,Ruby,Perl,Lazarus(Free Pascal)  
  6.   
  7. 其中 ASP、.NET、Java、Ruby、Python 和 PHP 版本除了提供客户端实现外,还提供了服务器端实现。  

HPROSE:

XML/HTML代码
  1. Hprose (High Performance Remote Object Service Engine) 是一个商业开源的新型轻量级跨语言跨平台的面向对象的高性能远程动态通讯中间件。它支持众多语言,例如 C++, .NET, Java, Delphi, Objective-C, ActionScript, JavaScript, ASP, PHP, Python, Ruby, Perl 等语言,通过 Hprose 可以在这些语言之间实现方便且高效的互通。  
  2.   
  3. Hprose 易学易用,且功能强大,您只需很短时间的学习,就可以用它方便地构建出跨语言跨平台分布式的电信级应用系统。  

如何在Yii中使用Hprose或者PHPRPC呢?我这里简单介绍一下Yii下hprose的应用方法

 

1、下载hprose的PHP版本,嗯,别看了,是混淆过的,但不影响你使用。

2、将下载后的hprose拷贝到yii项目的/protected/extension/hprose目录下

3、新建一个apicontroller:

大小: 43.99 K
尺寸: 299 x 376
浏览: 2113 次
点击打开新窗口浏览全图

我这样的方式是最简单的,将一些actionIndex的方法都公开了,在实际应用中当然不可以这样。不过我这里是测试,当然是无所谓的

访问http://localhost/project/test/ (project是我的项目名称,test是controller, index是action,由于默认action是index,所以我省略了)

浏览器中返回了:

XML/HTML代码
  1. Fa4{s11"actionIndex"s11"afterAction"s5"hello"s3"sum"}z  

由此其实我们也可以基本确认有四个方法可以使用actionIndex,afterAction,hello,sum,这主要是因为我把当前类当成发布对象了。(不主张啊不主张)

 

4、继续下一步,

PHP代码
  1. <?php
  2. include("./protected/extensions/hprose/hproseHttpClient.php");  
  3. $client = new HproseHttpClient("http://localhost/project/test");  
  4. $result = $client->sum(1,2,3,4,5);  
  5. print_r($result);  

 

OK,浏览器输出了15,就这样完成了一个简单的HPROSE应用。

当然我这样的方式太简单了,文档在这里有下载,我就不再画蛇添足的提供了:http://www.hprose.com/documents.php。

因为只是简单的的一些应用,暂时也看不到hprose的性能比phprpc提升了多少。

---------------备注

由于Yii对于大小写敏感,因此在new HproseHttpServer();的时候,Hprose的H不能大写,否则,它会自动寻找HproseHttpServer.php,但由于PHP的hprose的文件中首字母都是小写。因此在new的时候就需要:new hproseHttpServer();

Tags: yii, hprose, phprpc