2011-01-05 10 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

これはかなり曖昧です。 「高度なOOPの概念」とは何ですか、なぜそれらを使用したいのですか?今のように、特にPHPが読み取りアクセス権を持っている限り、攻撃者があなたが望むWebサーバーからファイルを簡単にダウンロードできるということを心配する必要があります。 (ヒント:クエリ文字列のファイル名に基づいてファイルを読み取り、その内容を送信しています) – tdammers

+0

@tdammersその他のもの:) – XMen

+0

コードを分割していますが、大きなメソッドがなく、複数の小さなメソッドがあります。たとえば、 "if video"と "if audio"がすべて同じように見える場合(重複したコードを処理するメソッドを呼び出すことができると確信しています。これはヘルパーメソッドです。 eleseのどこかで使ってください)。メソッドのドキュメント(各メソッドが何を行うのか、どのようなパラメータが期待されるのかなど)を追加します。 –

答えて

1

- あなたのクラスは、(あなたが任意のプロパティを持っていない)より「サービス」クラスのようであるように思わ

コメント。次に、クラスのインスタンスが1つだけ必要です。シングルトンパターンを実装します。インスタンスが頻繁に使用されたり作成されたりした場合は、ほとんどすべてのメソッドを呼び出します。複数の接続を避けるためにDB属性を作成します(実際にはアプリケーションスコープのシングルトンで行うことができます)。そのすべてはあなたのクラスの使用方法に依存します。

- シングルトンパターンについて/コメント

thisをお読みください。

DB属性については、メソッドのいくつかのローカル変数ではなく、Contentクラスのインスタンスごとに1回だけ接続することができます。

DBを必要とするメソッドを複数回呼び出す場合は、現時点ではあなたのケースではないことがあります。ここで

は一例です:

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

関連する問題