2011-01-05 6 views
0

Ich habe diesen Klasseninhalt, in dem ich s3 und sdb Klasse verwende, wie kann ich diese Klassenstruktur verbessern, um erweiterte oop Konzepte zu verwenden.oop concept implementation

<?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; 
     } 
    } 



} 


?> 

Verwenden der Klasse von diesem Code:

$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

Das ist ziemlich vage. Was sind "fortgeschrittene OOP-Konzepte" und warum möchten Sie sie verwenden? Wie es jetzt ist, müssen Sie sich andere Sorgen machen, besonders die Tatsache, dass ein Angreifer leicht jede Datei von Ihrem Webserver herunterladen kann, solange PHP Lesezugriff hat. (Hinweis: Sie lesen eine Datei basierend auf einem Dateinamen aus der Abfragezeichenfolge und senden dann ihren Inhalt) – tdammers

+0

@tdammers Irgendetwas anderes :) – XMen

+0

Split Sie sind Code mehr, haben keine großen Methoden stattdessen mehrere kleine Wenn beispielsweise "Wenn Video" und "Wenn Audio" gleich aussehen (ich bin mir sicher, dass Sie eine Methode verwenden können, die den doppelten Code verarbeitet, könnte dies eine Hilfsmethode sein, eine private Methode, wenn Sie nicht planen benutze es irgendwo elease). Fügen Sie Methodendokumentation hinzu (was jede Methode macht und wann sie aufgerufen werden sollte, welche Parameter erwartet werden usw.). –

Antwort

1

- Kommentar

Ihre Klasse scheint eher wie ein "Service" Klasse zu sein (Sie haben noch keine Eigenschaft haben). Dann brauchen Sie nur eine Instanz der Klasse: Implementieren Sie das Singleton-Muster. Wenn die Instanz häufig verwendet oder einmal erstellt wird, rufen Sie fast alle Methoden auf: Erstellen Sie ein DB-Attribut, um mehrere Verbindungen zu vermeiden (tatsächlich könnten Sie dies mit einem Singleton im Anwendungsbereich der Anwendung tun). All das hängt von Ihrer Art der Nutzung der Klasse ab.

-/Kommentar

für das Singletonmuster, lesen this.

Über das DB-Attribut können Sie nur einmal für jede Instanz der Inhaltsklasse anstelle mehrerer lokaler Variablen in Methoden eine Verbindung herstellen.

Es könnte nützlich sein im Falle von mehreren Aufrufen von Methoden, die DB benötigen, was momentan nicht der Fall ist. Hier

ein Beispiel:

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 Abstimmung für die Erstellung von Datenbankeigenschaften – XMen