addressbook.class.php
changeset 6 48ffdc97f54b
parent 5 879f0956be86
child 7 47446e75ceea
equal deleted inserted replaced
5:879f0956be86 6:48ffdc97f54b
     1 <?
     1 <?
       
     2 
     2 interface Address_Book {
     3 interface Address_Book {
     3     public function get_entries();
     4     public function get_entries();
     4     public function search_entries($pattern);
     5     public function search_entries($pattern);
     5     public function add_entry($entry);
     6     public function add_entry($entry);
     6 }
     7 }
       
     8 
       
     9 class Address_Book_Exception extends Exception { }
     7 
    10 
     8 class Address_Book_File implements Address_Book {
    11 class Address_Book_File implements Address_Book {
     9 
    12 
    10     const RS = "\n";
    13     const RS = "\n";
    11     const FS = "\t";
    14     const FS = "\t";
    13     private $fh;
    16     private $fh;
    14     private $file;
    17     private $file;
    15 
    18 
    16     function __construct($file) {
    19     function __construct($file) {
    17 	@mkdir(dirname($file));
    20 	@mkdir(dirname($file));
    18 	$this->fh = fopen($file, "a+b");
    21 	@$this->fh = fopen($file, "a+b");
       
    22 	if (!$this->fh) throw new Address_Book_Exception("Can't open address book.");
    19 	flock($this->fh, LOCK_EX);
    23 	flock($this->fh, LOCK_EX);
    20 	$stat = fstat($this->fh);
    24 	$stat = fstat($this->fh);
    21 	if ($stat['size'] == 0) {
    25 	if ($stat['size'] == 0) {
    22 		fputs($this->fh, join(self::FS, array("Hans Hanson", "0815", "hans@hanson.de"))
    26 		fputs($this->fh, join(self::FS, array("Hans Hanson", "0815", "hans@hanson.de"))
    23 			. self::RS);
    27 			. self::RS);