OOP
authorHeiko Schlittermann (IT Trainingshaus) <hs@schlittermann.de>
Wed, 26 Oct 2011 14:39:18 +0200
changeset 11 fb55da5ecb8a
parent 10 2a05edf9dc87
child 12 873ac3cadb02
OOP
class.Address_Book_File.php
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/class.Address_Book_File.php	Wed Oct 26 14:39:18 2011 +0200
@@ -0,0 +1,70 @@
+<?
+require "interface.Address_Book.php";
+
+class Address_Book_File implements Address_Book {
+	const RS = "\n";
+	const FS = "\t";
+
+	private $fh;
+	public function __construct($file) {
+		@mkdir(dirname($file));
+		$this->fh = fopen($file, "a+b");
+		if (!$this->fh) {
+			throw new Exception("Oooops, Problem mit $file");
+		}
+		flock($this->fh, LOCK_EX);
+		$stat = fstat($this->fh);
+		if ($stat['size'] == 0) {
+			fputs($this->fh, join(self::FS, array("Hans Hanson", "0815", "hans@hanson.de"))
+				. self::RS);
+		}
+		flock($this->fh, LOCK_SH);
+		fseek($this->fh, 0, SEEK_SET);
+	}
+
+	public function get_all_entries() {
+		$entries = array();
+		fseek($this->fh, 0, SEEK_SET);
+		while($line = stream_get_line($this->fh, 0, self::RS)) {
+			if ($line === FALSE) break;
+			$entries[] = explode(self::FS, $line);
+		}
+		return $entries;
+	}
+
+	public function add_entry($entry) {
+		$fields = array('name', 'tel', 'mail');
+		$new = array();
+		foreach($fields as $key) {
+			if (!isset($entry[$key])) return;
+			$new[$key] = $entry[$key];
+			trim($new[$key]);
+			preg_replace('/['.self::RS.self::FS.' ]+/', ' ', $new[$key]);
+			if (empty($new[$key])) return;
+		}
+
+		flock($this->fh, LOCK_EX);
+		fputs($this->fh, join(self::FS, $new) . self::RS);
+		flock($this->fh, LOCK_UN);
+		header("Location: $_SERVER[PHP_SELF]?action=add");
+		exit;
+	}
+
+	public function search_entries($pattern) {
+		fseek($this->fh, 0, SEEK_SET);
+		$entries = array();
+		while ($line = stream_get_line($this->fh, 0, self::RS)) {
+			if ($line === FALSE) break;
+			if (!preg_match("/$pattern/i", $line)) continue;
+			$entry = explode(self::FS, $line);
+			$entries[] = array('name' => $entry[0],
+					   'tel' => $entry[1],
+					   'mail' => $entry[2]);
+		}
+		return $entries;
+	}
+
+	public function delete_entries($ids) { }
+}
+
+?>