1. Go to this page and download the library: Download grithin/record library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
# Lets make a mock database
$database_records = [
1=>[
'id'=>1,
'name'=>'bob',
'children' => '[{"name":"sue"}]'
]];
#+ make the getter and setter methods {
$get_from_db = function($Record) use ($database_records){
return $database_records[$Record->id];
};
$set_to_db = function($Record, $changes) use ($database_records){
$record_data = $database_records[$Record->id];
$record_data= \Grithin\Dictionary::diff_apply($record_data, $changes);
$database_records[$Record->id] = $record_data;
return $record_data;
};
#+ }
# initialize the record, using the 'id' option
$record = new \Grithin\Record(false, $get_from_db, $set_to_db, ['id'=>1]);
$record->get();
# let's capitalize the name when we set it
$capitalize_name = function($Record, $diff){
if(isset($diff['name'])){
$diff['name'] = strtoupper($diff['name']);
}
};
$record->before_change($capitalize_name);
$record['name'] = 'bill';
# the name will become capitalized because of the event listener
$record['name']; #> BILL
# the children key points to a JSON string
$record['children']; #> '[{"name":"sue"}]'
# We can make it so JSON is automatically encoded and decoded when moving between the database
$jsonify = function($Record, $diff){
if(isset($diff['children'])){
$diff['children'] = json_encode($diff['children']);
}
};
$unjsonify = function($Record){
if(isset($Record['children'])){
$Record->record['children'] = json_decode($Record->record['children'], true);
}
};
$record->after_get($unjsonify);
$record->before_update($jsonify);
$record->get();
# now can access the full structure
$record['children'][0]['name']; #> sue
$record['children'][0]['name'] = 'jan';
$record->save(); # will encode the json for the db, then decode it for regular access
$record['children'][0]['name']; #> 'jan'
var_export($database_records);
/* >
array (
1 =>
array (
'id' => 1,
'name' => 'bob',
'children' => '[{"name":"sue"}]',
),
)
*/
# update local copy
$Record->local_update(['name'=>'bill', 'age'=>1]);
# update both
$Record->update(['name'=>'bill', 'age'=>1]);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.