Location: PHPKode > scripts > PHP DB Object > class.dbobject.php
<?php
   /**
   * Core DBObject is a self expanding class which stores all system data.
   * @name  		DBObject
   * @author		Christian Uhl
   * @copyright		Christian Uhl
   * @version  1.0.3
   *///BEKANNTE BUGS: IN (~ !~ nicht implementiert
   class DBobject
   {
   	
   	function __construct($var=false)
   	{
   		if(is_db($var))
   			$this->iobject($var);
   	}
   	
   	
   	/**
	* Converts an Array or DBobject in an JS Array --- can also be a normal string
	* @return	string	Javascript Array Code
	* @param	mixed	$array	Can be Array OR DBobject
	* @example 	in JS: "var JSARRAY = ".Array2JS($phparray);
	* @access	public
	*/
	public function toJS($array=false)
	{
		if(!$array) $array = $this;
		if(!is_db($array))
		{
			if ($array === null)
				return 'null';
			return '"' . str_replace(array("\r\n", "\n", "\r"), ' ', $array) . '"';
		} 
        
		$return = "{";
		$first = true;
		foreach($array as $key => $value)
		{
			if (!$first)
				$return .= ', ';
			$first = false;
			if (is_string($key) )
			{
				$key = '"' . $key . '"';
			}
	
			$return .= $key . ' : ' . $this->toJS($value);
		}
		return $return . "}";
	}
	
   	/**
   	* php standard __toString
   	* @description	allows to print every dbObject (easy debugging)
   	* @return		status msg after finishing
   	* @access		public
   	*/
   	public function __toString() {
   		echo '<pre>';
   		var_dump($this);
		echo '</pre>';
		return 'Object printed';
   	}
   	
	/**
	* Request function
	*
	* Returns a variable (required for numeric variables)
	* @param	string	$id	Variablename
	* @return	mixed	Variable
	* @access	public
	*/
	public function r($id)
	{
		foreach($this as $iid => $obj)
			if($iid == $id)
				return $obj;
	}

	/**
	* Iobject
	*
	* Converts an Array in a DBObject
	* @param	array	$array	Array
	* @param	object	$object	Target Object
	* @return	object	Target Object
	* @access	public
	*/
	public function iobject($array=false,$object=false)
	{
	        	if(!$object) $object = $this;
	        	if($array instanceof DBobject)
	            {
	           		$object = $array->copy();
	           		return $object;
	            }
	            elseif(is_object($array))
	            {
	            	$array = (array)$array; //Casten wir halt :P
	            }
	            
	            if(is_array($array))
	            {
	                foreach($array as $var => $wert)
	                {
	                    if(is_array($wert))
	                        $object->$var = $this->iobject($wert,new DBobject());
	                    else
	                        $object->$var = $wert;
	                }
	            }
	            return $object;
	}

	/**
	* export
	*
	* Converts an DBObject in an Array
	* @param	object	$obj	Source Object
	* @return	array
	* @access	public
	*/
	public function export($obj=false)
	{
	if(!$obj) $obj = $this;
	foreach($obj as $key => $value)
	               {
	               if($value instanceof DBobject)
	                        $return[$key]=$this->export($this->$key);
	               else
	                        $return[$key]=$value;
	               }
	return $return;
	}


	/**
	* count
	*
	* Counts the size of a DBObject
	* @param	object	$dbobj	Source Object
	* @return	int	Size
	* @access	public
	*/
	public function count($dbobj=false)
	{
	$x = 0;
	            if(!$dbobj) $dbobj = $this;
	            if($dbobj instanceof DBobject)
	            {
		            foreach($dbobj as $var) $x++;
		            return $x;
	            }
	}
	
	public function isEmpty($dbobj = false)
	{
		if(!$dbobj) $dbobj = $this;
		if($dbobj instanceof DBobject)
	            {
		            foreach($dbobj as $var) return false;
		            return true;
	            }
	}

         	/**
	* order - Quicksort
	*
	* Orders the Object - own implementation of quicksort
	* @param	string	$what	Order By - only in multidimensional Arrays --- if not set: works like array_sort
	* @param	object	$dbobj	Source Object
	* @return	object
	* @access	public
	*/
	public function order($how=false,$dbobj=false)
	{
	            if(!$dbobj) $dbobj = $this;

	            $x = false;
	            $lower = new DBobject();
	            $higher = new DBobject();


	            if(is_array($how))
	            	$what = $how[0];
		else $what = $how;

	            if($this->count($dbobj) <= 1) return $dbobj;

	           if($dbobj instanceof DBobject)
	           {
	            foreach($dbobj as $key => $value)
	            {
	                if($x == false)
	                {
	                    if($what)
	                    	$keyValue = $value->$what;

	                    else $keyValue = $value;

	                        $thisKey = new DBobject();
	                        $thisKey->$key = $value;
	                        $x = true;

	                }
	                else
	                {
	                    if(!$what)
	                    {
	                        if($value < $keyValue) //Kleiner
	                           $lower->$key = $value;
	                        elseif($value > $keyValue) //Grš§er
	                            $higher->$key = $value;
	                        elseif($value == $keyValue) //Gleichgro§
	                           $thisKey->$key = $value;
	                    }
	                    elseif(isset($value->$what))
	                    {
	                        if($value->$what < $keyValue) //Kleiner
	                           $lower->$key = $value;
	                        elseif($value->$what > $keyValue) //Grš§er
	                            $higher->$key = $value;
	                        elseif($value->$what == $keyValue) //Gleichgro§
	                            $thisKey->$key = $value;
	                    } else
	                     return false;
	                }
	            }

	            if(strtolower($how[1]) == 'desc')
	            		$return = $this->merge(array($this->order($how,$lower),$thisKey,$this->order($how,$higher)));
	            else
		            $return = $this->merge(array($this->order($how,$higher),$thisKey,$this->order($how,$lower)));
	           }
	           unset($lower);
	           unset($higher);
	           unset($thisKey);
	           return $return;
	}

    /**
	* merge
	*
	* merges many Objects
	* @param	array	$array	Can be an Array with Objects OR the first object
	* @param	array	$object2 Second Object wo Merge with first
	* @param 	bool	$overwrite Overwrite if same Subkey exists or rename it.
	* @return	object
	* @access	public
	*/
	public function merge($array,$object2=false,$overwrite=false)
	{
	//func_get_args
	$return = new DBobject();

	if(is_array($array))
		$rlarray = $array;

	if($array instanceof DBobject)
		$rlarray[] = $array;

	if($object2 instanceof DBobject)
		$rlarray[] = $array2;

		         foreach($rlarray as $arr)
		         {
		            if($arr instanceof DBobject)
		            {
		                foreach($arr as $key => $value)
		                {
		                if($return->$key && $overwrite === false)
		                    {
		                    $x = 0;
		                    $skey = $key.$x;
		                        while($return->$skey)
		                        {
		                            $x++;
		                            $skey = $key.$x;
		                        }
		                    $return->$skey = $value;
		                    }
		                else
		                    $return->$key = $value;
		                }
		            }
		         }
	unset($array);
	unset($object2);
	return $return; //->copy() von nšten?
	}

	private function filterit($obj,$command)
	{
	preg_match('/^(".*?"|[^"].*?)(==|<=|>=|!=|<|>|~|!~)(".*?"|[^"].*)$/',$command,$est);
	$db = new DBobject();
	if(is_db($obj))
	{
	foreach($obj as $key => $value)
		{
		   if($est[2] != '~' && $est[2] != '!~')
		   {
			  //Checken ob Variable oder String als Ident gewŸnscht fŸr BEIDE seiten
			  if(substr($est[3], -1, 1) == '"' && substr($est[3], 0, 1) == '"')
			  {
				$var2 = substr($est[3], 1, -1);
			  } else
			  {
				$var2 = $value->$est[3];
			  }
		
			  if(substr($est[1], -1, 1) == '"' && substr($est[1], 0, 1) == '"')
			  {
				$var = substr($est[1], 1, -1);
			  } else
			  {
				$var = $value->$est[1];
			  }
		    } else
		    { //Funktion fŸr WHERE MANY
		    	return $db;
		    }                		      
			switch($est[2])
			{
				case '!=':
				if(strpos($var2,'%') !== false)
				{
					$sumu = str_replace('%','(.*?)',$var2);
					if(!preg_match('/'.$sumu.'/',$var))
						$db->$key = $value;

				} else
				{
				if($var != $var2)
						$db->$key = $value;
				}
				break;

				case '==':
				if(strpos($var2,'%') !== false)
				{
					$sumu = str_replace('%','(.*?)',$var2);
					if(preg_match('/'.$sumu.'/',$var))
						$db->$key = $value;

				} else
				{
					 if($var == $var2)
							$db->$key = $value;
				}
				break;

				case '>':
				 if($var > $var2)
						$db->$key = $value;
				break;

				case '<':
				 if($var < $var2)
						$db->$key = $value;
				break;

				case '<=':
				 if($var <= $var2)
						$db->$key = $value;
				break;

				case '>=':
				 if($var >= $var2)
						$db->$key = $value;
				break;
			}
		}
		}
		return $db;
	}
	
    /**
	* Where
	*
	* exact the same like WHERE in mysql - works only in multidimensional Object.
	* Dont use this if you can filter the results before in an external DB System.
	* @param	array	$whereDB Where Array (ex: array(a==1,b==2,!,c==3) for if a==1 && b==2 || a==1
	* @param 	object	$dbobj	Source DB Object
	* @return	object
	* @access	public
	*/
	public function where($where,$dbobj=false)
	{
	//var_dump($where);
	if($dbobj == false) $dbobj = $this;
	if(!$where || !is_array($where)) //kein Where Array
		return false;


	         $what = array();
	         $current = 1;
	            //Split WHERE in OR (sodass nun nur noch AND operationen bleiben
	            foreach($where as $value)
	            {
	               if($value == '!' || $value == '|')
	                    $current++;
	               else
	                    $what[$current][]= $value;
	            }

	            foreach($what as $and)
	            {
	            $db = $dbobj->copy();

			          foreach($and as $estCmd)
			          {
			          $db = $this->filterit($db,$estCmd);		
			          }

	               
	            $return[] = $db;
	            }
	return $this->merge($return);
	}

    /**
	* Limit
	*
	* Limits the number of results
	* @param	array	$limit Limit Array(Begin,Howmuch) - exactly the same as the mysql limit.
	* @param 	object	$dbobj	Source DB Object
	* @return	object
	* @access	public
	*/
	public function limit($limit,$dbobj=false)
	{
	$x = 0;
	$return = new DBobject();
	if(!($dbobj instanceof DBobject)) $dbobj = $this;

	foreach($dbobj as $key => $value)
		{
		if($x >= $limit[0])
			{
			if($x <=$limit[0]+$limit[1])
				$return->$key = $value;
			else
				return $return;
			}
		$x++;
		}
	return $return;
	}

               /**
	* Copy
	*
	* creates an Hardcopy of an Object
	* @param	object	$db Source DB Object
	* @return	object
	* @access	public
	*/
	public function copy($db=false)
	{
	if($db == false) $db = $this;
		return unserialize(serialize($db));
	}

	/**
	* First
	*
	* Returns the First Result
	* @return	mixed
	* @access	public
	*/
	public function first()
	{
	foreach($this as $ds)
		{
		return $ds;
		}
	}
	
	/**
	* FirstKey
	*
	* Returns the First Key
	* @return	mixed
	* @access	public
	*/
	public function firstkey()
	{
	foreach($this as $key => $null)
		{
		return $key;
		}
	}

	public function dreturn($how)
	{
		$return = $this;
		switch($how)
		{
		case 'first':
			return $return->first();
		break;

		case 'id':
			return false;
		break;

		case 'bool':
			return true; //Wenn es soweit kommt ists eh true ;)
		break;

		case 'count':
			return $return->count();
		break;

		default:
			return $return->copy();
		break;
		}
	}
   }
?>
Return current item: PHP DB Object