00001 <?php 00002 /*************************************************************************** 00003 * Copyright (C) 2005-2007 by Konstantin V. Arkhipov * 00004 * * 00005 * This program is free software; you can redistribute it and/or modify * 00006 * it under the terms of the GNU Lesser General Public License as * 00007 * published by the Free Software Foundation; either version 3 of the * 00008 * License, or (at your option) any later version. * 00009 * * 00010 ***************************************************************************/ 00011 /* $Id: StorableDAO.class.php 4687 2007-12-09 18:57:18Z voxus $ */ 00012 00016 abstract class StorableDAO extends ProtoDAO 00017 { 00018 public function take(Identifiable $object) 00019 { 00020 return 00021 $object->getId() 00022 ? $this->save($object) 00023 : $this->add($object); 00024 } 00025 00026 public function add(Identifiable $object) 00027 { 00028 return 00029 $this->inject( 00030 OSQL::insert(), 00031 $object->setId( 00032 DBPool::getByDao($this)->obtainSequence( 00033 $this->getSequence() 00034 ) 00035 ) 00036 ); 00037 } 00038 00039 public function save(Identifiable $object) 00040 { 00041 return 00042 $this->inject( 00043 OSQL::update()->where( 00044 Expression::eqId($this->getIdName(), $object) 00045 ), 00046 $object 00047 ); 00048 } 00049 00050 public function import(Identifiable $object) 00051 { 00052 return 00053 $this->inject( 00054 OSQL::insert(), 00055 $object 00056 ); 00057 } 00058 00059 protected function inject( 00060 InsertOrUpdateQuery $query, Identifiable $object 00061 ) 00062 { 00063 $this->checkObjectType($object); 00064 00065 $db = DBPool::getByDao($this); 00066 00067 $query = 00068 $this->setQueryFields( 00069 $query->setTable($this->getTable()), 00070 $object 00071 ); 00072 00073 if ($query instanceof UpdateQuery) 00074 // can't be changed anyway 00075 $query->drop($this->getIdName()); 00076 00077 if (!$db->isQueueActive()) { 00078 $count = $db->queryCount($query); 00079 00080 $this->uncacheById($object->getId()); 00081 00082 if ($count !== 1) 00083 throw new WrongStateException( 00084 $count.' rows affected: racy or insane inject happened' 00085 ); 00086 } else { 00087 $db->queryNull($query); 00088 00089 $this->uncacheById($object->getId()); 00090 } 00091 00092 // clean out Identifier, if any 00093 return 00094 $this->identityMap[$object->getId()] 00095 = $object->setId($object->getId()); 00096 } 00097 } 00098 ?>