save object state?

liunx

Guest
ok... im not at home or i would test this myself. im at work (meant to be working), just running through some theories.

anyway, say i have a class. myclass, and in the class, i want a method that will serilise an instance of itself and then store that serilised object in the db. could i do it like this?

public function savestate() {
$state = serialize($this);
// save state to db.
}

or would i need to pass the instance in through an argument?

like isaid, im at work so cant test it. anyone know?don't ignore the functionality availability of __sleep()A common approach to object persistence is ORM (<!-- m --><a class="postlink" href="http://en.wikipedia.org/wiki/Object-relational_mapping">http://en.wikipedia.org/wiki/Object-relational_mapping</a><!-- m -->). There are some PHP packages out there such as Propel (<!-- m --><a class="postlink" href="http://propel.phpdb.org/trac/">http://propel.phpdb.org/trac/</a><!-- m -->) which is quite highly thought of. In essence you really have a layer between your domain and database layer which knows how to turn the properties of an object into an SQL statement, and vice versa.

class DomainObject
{
private $a, $b, $c;
public function setA( $value ) {}
}
class DomainObjectMapper
{
private $dblayer;
public function __construct( $dblayer )
{
$this->dblayer = $dblayer;
}
public function load( $id )
{
$data = $this->dblayer->query( /* SQL statement */ );
return new DomainObject( $data );
}
public function save( $object )
{
return $this->dblayer->query( /* SQL statement */ );
}
}
class MySqlDatabase
{
function query( $sql ) {}
}

$mapper = new DomainObjectMapper( new MySqlDatabase() );
$object = $mapper->load( 1 );
$object->setA( "new value" );
$mapper->save( $object );thanks shrike, that gives me a much better idea about how i should go about this.
 
Back
Top