PersistenceObjects for php

7. Add your own database methods

Of course there are situations where basic CRUD-operations are not enough. Implementing your own methods is quite easy.

Say we want to fetch users by their name and password.

require_once dirname(__FILE__)."/../lib/persistenceobjects/classes.php";
require_once dirname(__FILE__)."/../model/User.php";
require_once dirname(__FILE__)."/../model/Album.php";
require_once dirname(__FILE__)."/../model/Picture.php";

class UserPersistence extends PersistenceObject {
	
	...
	
	/**
	 * Fetches a User from database by it's $name and $password.
	 *
	 * @param string $name
	 * @param string $password
	 * @return User on success of false if none is found. Throws an exception.
	 */
	public function getByNameAndPassword($name, $password) {
		$dbMan = DatabaseManager::getInstance();
		
		$query = "select id from ".$this->tableName;
		$query .= " where name = '".mysql_real_escape_string($name)."'";
		$query .= " and password = '".mysql_real_escape_string(md5($password))."'";
		
		try {
			$res = $dbMan->executeQuery($query);
			
			if($row = mysql_fetch_assoc($res)) {
				$id = $row["id"];
			} else {
				return false;
			}
			
		} catch (Exception $e) {
			Logger::getInstance()->logError($e);
			throw $e;
		}
		
		return $this->get($id);
		
	}
}
previous - Use the PersistenceObjects in your controllers