oop concept implementation
I have this class content in which i am using s3 and sdb class how can i improve this class structure for using advanced oop concepts.
<?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.
开发者_如何学C * 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;
}
}
}
?>
Using the class by this 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;
}
-- comment
your class seems to be more like a "service" class (you don't have any property). Then you need just one instance of the class : implement the singleton pattern. If the instance is used quite often or once created, you call almost all methods : create a DB attribute to avoid multiple connections (actually you could do that with a singleton on the application scope). All of that depends on your way of use the class.
-- /comment
for the singleton pattern, read this.
About the DB attribute, it will allow you to connect just once for each instance of the Content Class instead of several local variables in methods.
It could be useful in case of multiple calls of methods that need DB which is not your case for the moment.
Here is an example :
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)){
精彩评论