Skip to content
Yo-An Lin edited this page May 30, 2017 · 6 revisions

Once you've defined your schema, you should be able to start using the model class. For example, if you have UserSchema, then you should have User, UserCollection and UserRepo.

We will demonstrate the CRUD operations:

To create an User object:

use UserBundle\Model\User;
$ret = User::create([ 
   'account' => 'c9s',
   'password' => 's3cket',
 ]);

The returned $ret object is Maghead\Runtime\Result, you can use the result object to check if the record is created successfully:

if ($ret->error) {
   // handle error
   die($ret->message);
}

$ret->error will be true if some error occurred, and then you can use $ret->message to get the error message.

In order to reduce the runtime overhead and to improve the flexibility for customization, Model::create does not catch the exceptions, so if you need to handle PDOException, then you should wrap the code with the try and catch block:

try {
   $ret = User::create($args);
   ...
} catch (PDOException $e) {
   ...
}

If you need to load the record immediately, you can call createAndLoad to return the created record object:

$user = User::createAndLoad($args);
if (false === $user) {
    // false will be returned if error happened.
}

To get the result, you may pass a referenced variable:

$user = User::createAndLoad($args, $ret);
if ($ret->error) {
   // ... handle error here.
}

Please note the createAndLoad method executes two SQL statements:

  1. Insert the row.
  2. Select the row with the lastInsertId

The record instance (domain object) provides few methods to help you get the correct data.

To get the current key of the record (primary key):

$id = $record->getKey();

To check if an instance has key:

if ($record->hasKey()) {
   ...
}

To get the name of the primary key:

$field = $record->getKeyName();
var_dump($field);  // => string "id"

To update the record (row) in the database:

$ret = $user->update([
   'email' => 'mj@gmail.com',
]);

Again, you can check the result by checking $ret->error:

$ret = $user->update([
   'email' => 'mj@gmail.com',
]);
if ($ret->error) {
   ....
}

To delete the record, you can do:

$ret = $user->delete();
if ($ret->error) {
   ....
}

To get the data stash:

$data = $record->getData();

To override the data loaded in the properties:

$record->setData([
   'email' => 'timcook@apple.com',
   'first_name' => 'Tim',
   'last_name' => 'Cook',
]);

See Also

If you have more than one database to manipulate the data, please visit Working with Repository to work on one table with multiple database connections.

Clone this wiki locally