2011-01-05 120 views
0

我有这个课程内容,我正在使用s3和sdb课程我如何改进这个课程结构以使用高级的oop概念。oop概念实现

<?php 
Class content{ 


    function getcontent(){ 
     if(!$_GET){ 
      echo "{'success':false, 'error':'No query parameters submitted'}"; 
      return; 
     } 
     // create connection 
     $sdb = new SimpleDB(awsAccessKey, awsSecretKey); 
     $condition = ""; 
     $status = ""; 
     //$params = json_decode(stripslashes($_POST['hash'])); 
     $params = $_GET; 
     unset($params['command']); 
     foreach($params as $key => $value){ 
      $condition .= " " . $key . " = '" . $value . "' and" ;  
     } 

     $condition = preg_replace('/and$/', "", $condition); 
     if($condition!='') 
     $condition=" and ".$condition; 
     $query = "select * from ".domain; 

     if($condition!= " _empty_ = '' "){ 
      $query .= " where time_stamp is not null $condition order by time_stamp asc"; 
     } 
     //~ echo $query; 

     $fileHash = '{'; 
     if($files = $sdb->select($domain, $query)){ 
      $status = 'true'; 

     }else{ 
      $status = 'false'; 
      $files= array(); 
      $message = "No records retrieved from SimpleDB ".json_encode($sdb->ErrorCode); 
     } 
     $array=array(
      'files'=>$files, 
      'success'=>$status, 
      'message'=>$message 
     ); 

     echo (json_encode($array)); 


    } 
    function getthumb(){ 
     $_url = $_REQUEST['url']; 
     $url=''; 
     if ($_url != "") { 
      echo $url = file_get_contents("$_url"); 

     } 
     return $url; 
    } 
    function upload(){ 
     //instantiate the S3 class 
     $s3 = new S3(awsAccessKey, awsSecretKey); 

     //instantiate the SimpleDB class 
     $sdb = new SimpleDB(awsAccessKey, awsSecretKey); 

     // Set temp directory where files will be written temporarily 
     $uploaddir = 'uploads/'; 

     // Max file size 100 MB 
     $maxFileSize = 100 * 1024 * 1024; 

     $thumb = ''; 
     $status = ''; 
     $imgWidth = ''; 
     $imgHeight = ''; 

     // Get file size from Apache headers 
     $fileSize = getSize(); 

     // Get MIME type from Apache headers 
     $fileType = getFileType(); 

     if ($fileSize == 0){ 
      return array(success=>false, error=>"File is empty."); 
     }    
     if ($fileSize > $maxFileSize){ 
      return array(success=>false, error=>"File is too large."); 
     } 

     // Put data of pathinfo() array into $pathinfo 
     $pathinfo = pathinfo(getName()); 

     // Get file name - eg: myphoto 
     $filename = $pathinfo['filename']; 

     // Get extension - eg: .jpg 
     $ext = $pathinfo['extension']; 
     $originalName = $filename.'.'.$ext; 

     // Generate unique id for the current object 
     $randName = uniqid();  

     // Unique file name with extension 
     $fileTempName = $randName . '.' . $ext;  

     // Complete temp file name and path 
     $fullTempName = $uploaddir . $fileTempName; 

     // Upload the file to temp directory on .net server 
     save($fullTempName); 

     // If images, call the function imgThumbs() to generate thumbnails 
     if(preg_match("/^image/", $fileType)){ 
      $tbnail = $_GET['thumb_size']; 
      $thumb = imgThumbs($tbnail, $fullTempName, $fileType, bucket, cloudfront); 
      if($_REQUEST['profile_pic']=='y'){ 
       $crop_url=$thumb; 
      } 
      list($imgWidth, $imgHeight) = getimagesize($fullTempName); 
     } 

     // If videos, call convertVideo() and return path of converted video. Then call vidThumbs() to generate thumbnails 
     if(preg_match("/^video/", $fileType)){ 
      $fullTempName = convertVideo($fullTempName, $fileType);   // Capture filename with complete path and flv extension 
      $fileTempName = preg_replace('/^uploads\//', '', $fullTempName);// Remove directory to get only the filename of flv 
      $fileType = "video/x-flv";          // Assign $fileType 
      $randName = substr($fileTempName, 0, 13);      // Parse and assign the unique id to $randName 
      $imgWidth = 120;            // Hardcoding width of video thumbnail 
      $imgHeight = 90;            // Hardcoding height of video thumbnail 
      $thumb = vidThumbs($fullTempName, bucket, cloudfront);  // Call the video thumbnail func 
     } 

     // If audio, call convertAudio() and return path of converted audio. 
     if(preg_match("/^audio/", $fileType)){ 
      $fullTempName = convertAudio($fullTempName, $fileType);   // Capture filename with complete path and mp3 extension 
      $fileTempName = preg_replace('/^uploads\//', '', $fullTempName);// Remove directory to get only the filename of mp3 
      $fileType = "audio/mpeg";          // Assign $fileType 
      $randName = substr($fileTempName, 0, 13);      // Parse and assign the unique id to $randName 
      $imgWidth = $imgHeight = 100;         // Hardcoding for positioning the thumbnail for audio 
      $thumb = 'http://dtzhqpwfdzscm.cloudfront.net/4c7247570bd4b.jpg'; // Hardcoding this url for audio thumbs 
     } 

     // Metadata for SimpleDB 
     $contentObjectType = "upload"; 
     $timeStamp = time(); 
     $url = cloudfront.$fileTempName; 
     $on_floor = "true"; 

     /* 
     * An array of (name => (value [, replace])), 
     * where replace is a boolean of whether to replace the item. 
     * replace is optional, and defaults to false. 
     * If value is an array, multiple values are put. 
     */ 
     $putAttributesRequest = array(
      "contentid"   => array("value" => "$randName"),   // unique id for EVERY object and link 
      "content_obj_type" => array("value" => "$contentObjectType"), // whether link or file upload 
      "file_name"   => array("value" => "$fileTempName"),  // unique generated filename 
      "url"    => array("value" => "$url"),    //file's CDN url 
      "original_name"  => array("value" => "$originalName"),  //original name of the file 
      "file_size"   => array("value" => "$fileSize"),   //size of file uploaded 
      "time_stamp"  => array("value" => "$timeStamp"),   //time 
      "file_type"   => array("value" => "$fileType"),   //mime type of uploaded file 
      "thumb"    => array("value" => "$thumb"),    //thumbnail link 
      "width"    => array("value" => "$imgWidth"),   //width of uploaded image 
      "height"   => array("value" => "$imgHeight"),   //height of uploaded image 
      "on_floor"   => array("value" => "$on_floor")   //by default all cObj on floor 
     ); 

     // Get ALL the parameter hash passed 
     $contentObjHash = getParam();          
     foreach($contentObjHash as $key => $value){ 
      $putAttributesRequest["$key"] = array("value" => "$value"); 
     } 

     //check whether a form was submitted 
     if(isset($fileTempName)){ 

      // Begin object hash here 
      $objHash = '{'; 

      /* Move the file to S3 
      * 
      * @param mixed $fileTempName Location of temp file 
      * @param string bucket Bucket 
      * @param string $newFileName Unique generated file name 
      * @param constant ACL 
      * @param array() Dont worry about this 
      * @param string $fileType MIME type of file 
      * @return boolean 
      */ 
      if($_REQUEST['profile_pic']!='y' && !$s3->putObjectFile($fullTempName, bucket, $fileTempName, S3::ACL_PUBLIC_READ, array(), $fileType)) { 
       $status = 'false'; 
       $objHash .= "success : ".json_encode($status)."}";   // End object hash here id S3 error 
       echo $objHash;    
       return; 
      } 

      /** 
      * Create or update attributes 
      * 
      * @param string $domain Domain 
      * @param string $randName Unique generated file name 
      * @param array $putAttributesRequest See up for more info 
      * @return boolean 
      */          
      if($sdb->putAttributes(domain, $randName, $putAttributesRequest)){ 
       $status = 'true'; 
       unlink($fullTempName); 
      }else{ 
       $status = 'false'; 
       $objHash .= "'SimpleDB_error' : ".json_encode($sdb->ErrorCode).","; 
      } 

      foreach($putAttributesRequest as $key => $value){ 
       $objHash .= json_encode($key). " : " . json_encode($value["value"]) .", "; 
      } 

      $objHash .= "'success' : ".$status."}";    // End object hash after SimpleDB transaction 

      echo $objHash; 
     } 
    } 



} 


?> 

使用类这段代码:

$content=new content(); 
switch($command){ 
    case 'getcontent': 
     $content->getcontent(); 
     break; 
    case 'thumb': 
     $content->getthumb(); 
     break; 
    case 'upload': 
     $content->upload(); 
     break; 
    case 'update': 
     $content->update(); 
     break; 
    default: 
     break; 
} 
+1

这是非常模糊的。什么是“高级面向对象概念”,以及为什么要使用它们?就像现在一样,您还有其他需要担心的事情,特别是攻击者可以轻松地从您的webserver上下载任何他们想要的文件,只要PHP具有读取权限即可。 (提示:您正在根据查询字符串中的文件名读取文件,然后发送其内容) – tdammers 2011-01-05 06:55:48

+0

@tdammers其他任何东西:) – XMen 2011-01-05 07:22:40

+0

拆分你的代码更多,没有大的方法,而是有多个小的方法,例如“如果视频”和“如果音频”看起来一模一样(我敢肯定你可以提供一个方法来处理重复的代码,这可能是一个辅助方法,如果你不打算在某处使用它)。添加方法文档(每个方法的作用和应该何时调用,它期望什么参数等等)。 – 2011-01-05 07:34:21

回答

1

- 评

类似乎更像是一个“服务”类(你没有任何属性)。然后你只需要一个类的实例:实现单例模式。如果实例经常使用或创建一次,则几乎可以调用所有方法:创建一个DB属性以避免多重连接(实际上,您可以在应用程序范围内使用单例执行此操作)。所有这些都取决于你的课堂使用方式。

- /评论

单例模式,阅读this

关于DB属性,它将允许您仅为Content Class的每个实例连接一次,而不是在方法中连接多个局部变量。

对于需要使用数据库的方法的多次调用而言,它可能非常有用,但目前情况并非如此。

下面是一个例子:

Class content{ 

    private $db=null; // db 

    public function __construct(){ // CONSTRUCTOR : called with the new operator 
     // create connection (created once for the instance) 
     $this->db = new SimpleDB(awsAccessKey, awsSecretKey); 
     // you can pass the connection strings as parameter 
    } 

    public function getcontent(){ 

     // You should not use directly GET here : pass it as parameter 
     // as the origin of the data may change some day 
     // in this method, it doesn't where the data come from 
     // -> encapsulation : the code keeps consistent when environment changes 
     if(!$_GET){ 
      echo "{'success':false, 'error':'No query parameters submitted'}"; 
      return; 
     } 

     ... 

     // query something using the local attribute 
     if($files = $this->db->select($domain, $query)){ 
+0

+1投票制作数据库属性 – XMen 2011-01-05 09:33:39