组合PHP类,而不是填充数组

时间:2016-01-27 14:17:13

标签: php arrays class

我在同一个命名空间(PhotoProject)中有3个不同的类(Thumbnail.php中的Thumbnail类,Upload.php中的Upload类和ThumbnailUpload.php中的ThumbnailUpload类)。目前,它将加载图像,创建缩略图并将其存储在所选目录中,但它不会将请求的信息存储到数据库中。如果查看blog_insert.php的代码片段,一旦调用$ loader-> collectFilenames分配给$ names,就不会在$ names []中存储任何内容。我做了一个var_dump,$ names总是空的。有什么建议?以下是代码段。

 class Upload {
 protected $collectednames = [];
 protected $typeCheckingOn = true;
 protected $notTrusted = ['bin', 'cgi', 'exe', 'js'];
 protected $newName;
 protected $destination; 
 protected $max = 8388608;
 protected $messages = []; 
 protected $permitted = [
  'image/gif',
  'image/png',
  'image/jpg'
]; 

 ...

 public function collectFilenames() {
 return $this->collectednames;

       }

blog_insert.php

 <?php

 use PhotoProject\ThumbnailUpload;
 require_once '../includes/connection.php';
 $conn = dbConnect();
 if (isset($_POST['insert'])) {

 $OK = false;

$stmt = $conn->stmt_init();
// if a file has been uploaded, process it
if(isset($_POST['upload_new']) && $_FILES['image']['error'] == 0) {
    $imageOK = false;

    require_once '../PhotoProject/ThumbnailUpload.php';
    $loader = new ThumbnailUpload('path to store images');
    $loader->setThumbDestination('path to store thumbnail'); 
    $loader->upload();
    $names = $loader->collectFilenames();

    // $names will be an empty array if the upload failed
    if ($names) {
        $sql = 'INSERT INTO images (filename, caption) VALUES (?, ?)';

班级缩略图

 <?php
 namespace PhotoProject;
 class Thumbnail {
   protected $original;
   protected $originalwidth;
   protected $originalheight;
   protected $basename;
   protected $thumbwidth;
   protected $thumbheight;
   protected $maxSize = 350;
   protected $canProcess = false;
   protected $imageType;
   protected $destination;
   protected $suffix = '_thb';
   protected $messages = [];

    public function __construct($image) {
    if (is_file($image) && is_readable($image)) {
        $details = getimagesize($image);
    } else {
        $details = null;
        $this->messages[] = "Cannot open $image.";
    }
    // if getimagesize() returns an array, it looks like an image
    if (is_array($details)) {
        $this->original = $image;
        $this->originalwidth = $details[0];
        $this->originalheight = $details[1];
        $this->basename = pathinfo($image, PATHINFO_FILENAME);
        // check the MIME type
        $this->checkType($details['mime']);
    } else {
        $this->messages[] = "$image doesn't appear to be an image.";
    }
  }

    public function setDestination($destination) {
    if (is_dir($destination) && is_writable($destination)) {
        // get last character
        $last = substr($destination, -1);
        // add a trailing slash if missing
        if ($last == '/' || $last == '\\') {
            $this->destination = $destination;
        } else {
            $this->destination = $destination . DIRECTORY_SEPARATOR;
        }
    } else {
        $this->messages[] = "Cannot write to $destination.";
    }
 }

    public function setMaxSize($size) {
    if (is_numeric($size) && $size > 0) {
        $this->maxSize = abs($size);
    } else {
        $this->messages[] = 'The value for setMaxSize() must be a positive      number.';
        $this->canProcess = false;
    }
  }

    public function setSuffix($suffix) {
    if (preg_match('/^\w+$/', $suffix)) {
        if (strpos($suffix, '_') !== 0) {
            $this->suffix = '_' . $suffix;
        } else {
            $this->suffix = $suffix;
        }
    } else {
        $this->suffix = '';
    }
}

    public function create() {
    if ($this->canProcess && $this->originalwidth != 0) {
        $this->calculateSize($this->originalwidth, $this->originalheight);
        $this->createThumbnail();
    } elseif ($this->originalwidth == 0) {
        $this->messages[] = 'Cannot determine size of ' . $this->original;
    }
}

    public function getMessages() {
    return $this->messages;
}

    protected function checkType($mime) {
    $mimetypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (in_array($mime, $mimetypes)) {
        $this->canProcess = true;
        // extract the characters after 'image/'
        $this->imageType = substr($mime, 6);
    }
}

    protected function calculateSize($width, $height) {
    if ($width <= $this->maxSize && $height <= $this->maxSize) {
        $ratio = 1;
    } elseif ($width > $height) {
        $ratio = $this->maxSize/$width;
    } else {
        $ratio = $this->maxSize/$height;
    }
    $this->thumbwidth = round($width * $ratio);
    $this->thumbheight = round($height * $ratio);
}

    protected function createImageResource() {
    if ($this->imageType == 'jpeg') {
        return imagecreatefromjpeg($this->original);
    } elseif ($this->imageType == 'png') {
        return imagecreatefrompng($this->original);
    } elseif ($this->imageType == 'gif') {
        return imagecreatefromgif($this->original);
    }
}

    protected function createThumbnail() {
    $resource = $this->createImageResource();
    $thumb = imagecreatetruecolor($this->thumbwidth, $this->thumbheight);
    imagecopyresampled($thumb, $resource, 0, 0, 0, 0, $this->thumbwidth,
      $this->thumbheight, $this->originalwidth, $this->originalheight);
    $newname = $this->basename . $this->suffix;
    if ($this->imageType == 'jpeg') {
        $newname .= '.jpg';
        $success = imagejpeg($thumb, $this->destination . $newname, 100);
    } elseif ($this->imageType == 'png') {
        $newname .= '.png';
        $success = imagepng($thumb, $this->destination . $newname, 0);
    } elseif ($this->imageType == 'gif') {
        $newname .= '.gif';
        $success = imagegif($thumb, $this->destination . $newname);
    }
    if ($success) {
        $this->messages[] = "$newname created successfully.";
    } else {
        $this->messages[] = "Couldn't create a thumbnail for " .
            basename($this->original);
    }
    imagedestroy($resource);
    imagedestroy($thumb);
}

}

类ThumbnailUpload

 <?php
 namespace PhotoProject;
 use PhotoProject\Upload;

 require_once 'Upload.php';
 require_once 'Thumbnail.php';

 class ThumbnailUpload extends Upload {

    protected $thumbDestination;
    protected $deleteOriginal;
    protected $suffix = '_thb';
    public function __construct($path, $deleteOriginal = false) {
    parent::__construct($path);
    $this->thumbDestination = $path;
    $this->deleteOriginal = $deleteOriginal;
 }

 /*
 ** Setter method for the thumbnail destination
 */
    public function setThumbDestination($path) {
    if (!is_dir($path) || !is_writable($path)) {
        throw new \Exception("$path must be a valid, writable directory.");
    }
    $this->thumbDestination = $path;
 }

    public function setThumbSuffix($suffix) {
    if (preg_match('/\w+/', $suffix)) {
        if (strpos($suffix, '_') !== 0) {
            $this->suffix = '_' . $suffix;
        } else {
            $this->suffix = $suffix;
        }
    } else {
        $this->suffix = '';
    }
  }

    public function allowAllTypes() {
    $this->typeCheckingOn = true;
  }

    protected function createThumbnail($image) {
    $thumb = new Thumbnail($image);
    $thumb->setDestination($this->thumbDestination);
    $thumb->setSuffix($this->suffix);
    $thumb->create();
    $messages = $thumb->getMessages();
    $this->messages = array_merge($this->messages, $messages);
}

    protected function moveFile($file) {
    $filename = isset($this->newName) ? $this->newName : $file['name'];
    $success = move_uploaded_file($file['tmp_name'],
        $this->destination . $filename);
    if ($success) {
        // add a message only if the original image is not deleted
        if (!$this->deleteOriginal) {
            $result = $file['name'] . ' was uploaded successfully';
            if (!is_null($this->newName)) {
                $result .= ', and was renamed ' . $this->newName;
            }
            $this->messages[] = $result;
        }
        // create a thumbnail from the uploaded image
        $this->createThumbnail($this->destination . $filename);
        // delete the uploaded image if required
        if ($this->deleteOriginal) {
            unlink($this->destination . $filename);   
        }
    } else {
        $this->messages[] = 'Could not upload ' . $file['name'];
    }
  }
}

班级上传

 <?php

 namespace PhotoProject;
 class Upload {
 protected $collectednames = [];
 protected $typeCheckingOn = true;
 protected $notTrusted = ['bin', 'cgi', 'exe', 'js'];
 protected $newName;
 protected $renameDuplicates;
 protected $destination;  
 protected $max = 8388608;
 protected $messages = [];
 protected $permitted = [
  'image/gif',
  'image/png',
  'image/jpg'
 ];

public function __construct($path) {
 if (!is_dir($path) || !is_writable($path)) {
    throw new \Exception("$path must be a valid, writable directory.");
    }
$this->destination = $path;
}

 public function setMaxSize($num) {
   if (is_numeric($num) && $num > 0) {
     $this->max = (int) $num;
  }
}


 public function allowAllTypes() {
   $this->typeCheckingOn = false;
    if (!$suffix) {
      $this->suffix = '';  // empty string
    }
 }

public function upload($renameDuplicates = true) {
$this->renameDuplicates = $renameDuplicates;
$uploaded = current($_FILES);
if (is_array($uploaded['name'])) {
    // deal with multiple uploads
    foreach ($uploaded['name'] as $key => $value) {
        $currentFile['name'] = $uploaded['name'][$key];
        $currentFile['type'] = $uploaded['type'][$key];
        $currentFile['tmp_name'] = $uploaded['tmp_name'][$key];
        $currentFile['error'] = $uploaded['error'][$key];
        $currentFile['size'] = $uploaded['size'][$key];
        if ($this->checkFile($currentFile)) {
            $this->moveFile($currentFile);
        }
    }
} else {
    if ($this->checkFile($uploaded)) {
        $this->moveFile($uploaded);
        }
    }
}

public function getMessages() {
return $this->messages;
}

public function collectFilenames() {
return $this->collectednames;

       }

public function getMaxSize() {
    return number_format($this->max/1024, 1) . ' KB';
}

protected function checkFile($file) {
    $accept = true;
        if ($file['error'] != 0) {
            $this->getErrorMessage($file);
            // stop checking if no file submitted
            if ($file['error'] == 4) {
               return false;
            } else {
                $accept = false;
            }
        }

        if (!$this->checkSize($file)) {
            $accept = false;
        }

        if ($this->typeCheckingOn) {
            if (!$this->checkType($file)) {
            $accept = false;
            }
        }

        if ($accept) {
            $this->checkName($file);
        }
        return $accept;
return true;
}

protected function checkName($file) {
    $this->newName = null;
    $nospaces = str_replace(' ', '_', $file['name']);
    if ($nospaces != $file['name']) {
        $this->newName = $nospaces;
    }
    $extension = pathinfo($nospaces, PATHINFO_EXTENSION);
    if (!$this->typeCheckingOn && !empty($this->suffix)) {
    if (in_array($extension, $this->notTrusted) || empty($extension)) {
        $this->newName = $nospaces . $this->suffix;
        }
    }
    if ($this->renameDuplicates) {
        $name = isset($this->newName) ? $this->newName : $file['name'];
        $existing = scandir($this->destination);
    if (in_array($name, $existing)) {
        // rename file
        $basename = pathinfo($name, PATHINFO_FILENAME);
        $extension = pathinfo($name, PATHINFO_EXTENSION);
        $i = 1;
        do {
            $this->newName = $basename . '_' . $i++;
            if (!empty($extension)) {
            $this->newName .= ".$extension";
            }
            } while (in_array($this->newName, $existing));
        }
    }
}

protected function getErrorMessage($file) {
switch($file['error']) {
    case 1:
    case 2:
        $this->messages[] = $file['name'] . ' is too big: (max: ' .
            $this->getMaxSize() . ').';
        break;
    case 3:
        $this->messages[] = $file['name'] . ' was only partially
            uploaded.';
        break;
    case 4:
        $this->messages[] = 'No file submitted.';
        break;
    default:
        $this->messages[] = 'Sorry, there was a problem uploading ' .
            $file['name'];
        break;
    }
}

protected function checkSize($file) {
    if ($file['error'] == 1 || $file['error'] == 2 ) {
        return false;
    } elseif ($file['size'] == 0) {
        $this->messages[] = $file['name'] . ' is an empty file.';
        return false;
    } elseif ($file['size'] > $this->max) {
        $this->messages[] = $file['name'] . ' exceeds the maximum size
            for a file (' . $this->getMaxSize() . ').';
        return false;
    } else {
        return true;
    }
}

protected function checkType($file) {
     if (in_array($file['type'], $this->permitted)) {
         return true;
     } else {
         if (!empty($file['type'])) {
            $this->messages[] = $file['name'] . ' is not permitted type of file.';
            return false;
         }
     }
 }

protected function moveFile($file) {
    $filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'],
    $this->destination . $filename);
if ($success) {
    // add the amended filename to the array of uploaded files
    $this->filenames[] = $filename;
    $result = $file['name'] . ' was uploaded successfully';
    if (!is_null($this->newName)) {
    $result .= ', and was renamed ' . $this->newName;
}
    $this->messages[] = $result;
    } else {
    $this->messages[] = 'Could not upload ' . $file['name'];
    }
  }
}

0 个答案:

没有答案