DB.PHP - PHP ORM

Save single object to table

If you know what class belongs an object you wish to save than you can use:

boolean $database->path->to->class->save (\path\to\class &$object [, integer $action=null]);

Returns true if succeeded and false if failed. Affects modifications to passed object. For example if you pass object with id is null and your table primary field is auto increment integer then after saving you will have newly assigned id in object's primary field specific property.

Warning ! Save method inserts when primary field property value is empty. Save method Updates when primary field property value is not empty.

There are cases when you want to force insert object in table while you also have primary field value already defined for that object. In this case you should use action parameter to specify save method how to act by passing \db\query::insert or \db\query::update as action value.

Example class:

class user
{
    public $id;
    public $name;
    public function __construct ($name)
    {
        $this->name = $name;
    }
}

Example usage which always will generate insert query because $user->id is null by default. If save succeedes than you will have newly assigned id in $user->id if id field for of user table is primary auto increment integer.

$user = new user ('John Smith');
if ($database->user->save($user))
{
    echo "user successfully saved.";
    echo "inserted user id is ".$user->id;
}
else
{
    echo "save failed";
}

Exmaple usage which will always generate update query:

//assuming we have user with id 1
$user = $database->user->load (1);
$user->name = 'John Drake';
if ($database->user->save($user))
{
    echo "user successfully renamed";
}
else
{
    echo "save rename failed";
}

Now let us define $user->id by ourself and force insert user

$user = new user ('John Next');
$user->id = 2;

if ($database->user->save ($user, \db\query::insert))
{
    echo "new user with predefined id was created";
}
else
{
    echo "save faield";
}

Note: Class handler always returns boolean value. True if save succeeded or false if failed. Along other reasons save might fail if you have denied update or insert for this table. You can deny insert or update with class php doc comments modifiers or from $database->path->to->class->insert = true/false / $database->path->to->class->update = true/false.