I came across this code snippet and confused with the cast() function? What does it do?
$userModel = new UserModel();
$record = $userModel->findone(array('id=?', $uid));
$f3->set('SESSION.deleteUser', $uid);
$f3->set('user', $record->cast());
$f3->set('content', 'user/delete.php');
$template = new \View;
echo $template->render('dashboard/layout.php');
It converts (aka "casts") a Mapper
object into an associative array
.
Before casting:
$userModel->load(['id=?',123]);
echo $userModel->id; // 123
echo $userModel->name; // John Doe
echo $userModel->country; // Botswana
print_r($userModel); // List of object properties (including inherited)
After casting:
print_r($userModel->cast());
/*
Array
(
[id] => 123
[name] => John Doe
[country] => Botswana
)
*/
Casting is useful when you want to pass a read-only copy of a mapper to a template (aka "separation of concerns"). It also helps reducing memory usage when loading a big number of records.