As
kilishan has already mentioned you should define $allowedFields within you model that's handling the entity.
This performs
array_intersect_keys against any given array or entity that your are trying to
save/
update or
insert.
Basically if you have:
PHP Code:
$this->allowedFields = ['user_id'];
And your incoming _POST array or keys in your Entity look similar to:
PHP Code:
[
'random' => 'stuff',
'bad' => 'things',
'user_id' => 1,
'get' => 'intersected'
]
Then only 'user_id' from example above gets passed to database. Now here's the point that I just cannot stress enough:
Always declare
$this->validationRules in your Model to make sure that keys that get passed: also get validated against expectations.
On the other hand: Maybe I got your question wrong and you wanted to know how can you Filter out
keys that you can store in the
$entity object itself?
If so here's a quick example to help anyone who's in need:
PHP Code:
<?php
class MyEntity
{
public int $user_id = 0;
# Add more local keys with default values here ...
# ...
# This 'magic' method makes sure every time you set
# current entity's local value it must be pre-existing.
public function __set(string $key, mixed $value): void
{
if (property_exists($this, $key)) {
$this->$key = $value;
}
}
# If you want to initiate entity with array of keys, ex:
# new Entity\MyEntity(['user_id' => 8]);
# then you would love to have a constructor like that:
public function __construct(array $dataset = [])
{
if (! empty($dataset)) {
foreach ($dataset as $key => $value) {
# Set each key.
$this->$key = $value;
}
}
}
}
Have fun!