Saturday, June 6, 2009

ArrayAccess: use object as an array, file manager example

ArrayAccess (PHP5) allows to treat objects as an array.
View below the interface scheme, with explanatory comments

ArrayAccess { //PHP5 built-in Interface
// returns true/false if the element in the position $offset exists/doesn't exist
abstract public boolean offsetExists ( string $offset )
// returns the element at the position $offset
abstract public mixed offsetGet ( string $offset )
// set the element at the position $offset to the value $value
abstract public void offsetSet ( string $offset , string $value )
//delete the element at the position $offset
abstract public void offsetUnset ( string $offset )
}

minimal implementation (to copy to quickly use).

class ... implements ArrayAccess
{
public function
offsetExists( $offset ){}
public function
offsetGet( $offset ){}
public function
offsetSet( $offset , $value ){}
public function
offsetUnset( $offset ){}
}


An useful example !
Let's write a class which allows to easily manage files content, like an array.

$obj["file.txt"] = "content"; //write "content" into file.txt
$obj["file.txt"] .= "content"; //append "content" into file.txt
print $obj["file.txt"] ; //print the content of file.txt
unset($obj["file.txt"]); //delete file.txt
if (isset($obj["file.txt"])) {} ; // equivalent to file_exists("file.txt")


/* class to easy manage files content like an array */
class filesManager implements ArrayAccess
{
private $basePath;
private
$prefix;
private
$suffix;

public function
__construct($basePath="", $prefix="", $suffix=""){
$this->basePath = $basePath;
$this->prefix = $prefix;
$this->suffix = $suffix;
}

//get files basepath + prefix
private function path($file){
return
$this->basePath.$this->prefix.$file.$this->suffix;
}

//file exists ?
public function offsetExists( $file ){
return
file_exists($this->path($file));
}

//read file
public function offsetGet( $file ){
if (!
$this->offsetExists($file)) return "";
$handle = fopen($this->path($file), "r");
$contents = fread($handle, filesize($this->path($file)));
fclose($handle);
return
$contents;
}

//write new content into a file
public function offsetSet( $file , $value ){
$handle = fopen($this->path($file), "w");
fwrite($handle, $value);
fclose($handle);
}

//delete file
public function offsetUnset( $file ){
unlink($this->path($file));
}

}




//example of use

/* the files will be read and created in
* the folder "data", with prefix "_" and
* suffix ".txt" */
$f = new filesManager("data/","_",".txt");

//create the file "data/_notes.txt" and write "file start" inside !
if (!isset($f['notes']))
$f['notes'] = "file start !";

//append
$f['notes'] .= "\nanother line";

//print all the content
print $f['notes'];

//delete
unset($f['notes']);

No comments:

Post a Comment

 

PHP and tips|PHP