You are not logged in.

This articles has been requested to be deleted.

This articles has been flagged as inappropriate.

Wednesday, September 29th 2010, 6:31pm

Tags

model, model view controller, mvc, object-relational mapping, objektorientierung, Objektrelationale Abbildung, Oo, ORM, PHP, php5

Abstract

Ein Model wird beim Model-View-Controller genutzt und enthält die Daten auf die der Controller zugreift um sie in der View darzustellen.

Article

1. Erläuterung


Der Code ist zur Hilfenahme entstanden, als die Frage geklärt werden sollte ob man die Validierung im Controller oder im Model praktizieren sollte: Überprüfung von Werten in $_POST Feldern. Mehr Informationen zum Basismodel sollen noch folgen. Jeder ist aber angehalten den Artikel zu verbessern.

Das hier erläutere Verfahren nutzt object-relational mapping bzw Objektrelationale Abbildung - kurz ORM.

2. Basismodel


PHP Quellcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
abstract class Model {
	protected $primarykey = 'id';
	protected $data = array();
 
	abstract public function getColumns();
 
	function __construct($data = array()) {
		$this->data = $data;
	}
 
	public static function findById($id, $className) {
		$sql = "SELECT	 *
			FROM	 ".$this->getTablename()."
			WHERE	 ".$this->primarykey." = :id ";
		$stmt = MyDB::getInstance()->prepare($sql);
		$stmt->execute(array(
			':id' => $id
		));
		return new $className($stmt->fetch());	
	}
 
	protected function _findById() {
	}
 
	public function __set($name, $value) {
		$this->data[$name] = $value;
	}
 
	public function __get($name) {
		return $this->data[$name];
	}
 
	/**
	 * empty() on a __get function will not work as expected if isset has not been overriden
	 */
	public function __isset($key) {
		if (isset($this->data[$key])) {
			return (false === empty($this->data[$key]));
		} else {
			return null;
		}
	}
 
	public function validate() {
 
	}
 
	public function getTablename() {
		return get_class($this);
	}
 
	public function delete() {
		$primaryval = $this->{$this->primarykey};
 
		$sql = 'DELETE FROM '.$this->getTablename().' WHERE '.$this->primarykey.' = :primaryval';
		$stmt = MyDB::getInstance()->prepare($sql);
		$stmt->execute(array(
			':primaryval' => $primaryval
		));
	}
 
	public function save($override = null) {
		if($override !== null) {
			$this->data = array_merge($this->data, $override);
		}
 
		$this->validate();
		$params = array();
		$primaryval = $this->{$this->primarykey};
 
		// insert or update		
		if($primaryval === null) {
			$sql = 'INSERT INTO '.$this->getTablename().' ('.implode(',', $this->getColumns()).') VALUES (';
			foreach($this->getColumns() as $key) {
				$sql .= ':'.$key.',';
				$params[':'.$key] = $this->$key;
			}
			$sql = rtrim($sql,',').')';
			if(count($params)) {
				$stmt = MyDB::getInstance()->prepare($sql);
				$stmt->execute($params);
 
				// remember auto increment key
				$this->{$this->primarykey} = MyDB::getInstance()->lastInsertId();
			}
		} else {
			$sql = 'UPDATE '.$this->getTablename().' SET ';
			foreach($this->getColumns() as $key) {
				$sql .= $key.' = :'.$key.',';
				$params[':'.$key] = $this->$key;
			}
			$sql = rtrim($sql,',').' WHERE '.$this->primarykey.' = :primaryval';
			if(count($params)) {
				$params[':primaryval'] = $primaryval;
				$stmt = MyDB::getInstance()->prepare($sql);
				$stmt->execute($params);
			}
		}
	}
}


3. Beispielimplementierung eines Benutzers


PHP Quellcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class User extends Model {
	public function getTablename() {
		return get_class($this); // user
	}
	public function getColumns() {
		return array('email', 'password');
	}
 
	public function validate() {
		if(...) {
			throw new ValidateException('message');
		}
	}
}


4. Beispiele


4.1. Neuen Benutzer anlegen


PHP Quellcode

1
2
3
4
5
6
7
8
9
10
11
<form method="post">
	email: <input type="text" name="email" /><br/>
	password: <input type="password" name="password" /><br/>
	<input type="submit">
</form>
<?php
if(count($_POST)) {
	$user = new User($_POST);
	$user->save();
}
?>


4.2. Benutzer bearbeiten


PHP Quellcode

1
2
3
4
5
6
7
8
9
10
11
<form method="post" action="edit.php?userid=123">
	email: <input type="text" name="email" /><br/>
	password: <input type="password" name="password" /><br/>
	<input type="submit">
</form>
<?php
if(count($_POST) && isset($_GET['userid'])) {
	$user = User::findById($_GET['userid']);
	$user->save($_POST);
}
?>

Lexikon 4.1.3, developed by www.viecode.com