diff --git a/dbObject.md b/dbObject.md index 07a7cf05..52ab9437 100644 --- a/dbObject.md +++ b/dbObject.md @@ -295,6 +295,42 @@ $products = product::arraybuilder()->paginate($page); echo "showing $page out of " . product::$totalPages; ``` + +###Hidden Fields +Sometimes it's important to block some fields that can be accessed from outside the model class (for example, the user password). + +To block the access to certain fields using the `->` operator, you can declare the `$hidden` array into the model class. This array holds column names that can't be accessed with the `->` operator. + +For example: + +```php +class User extends dbObject { + protected $dbFields = array( + 'username' => array('text', 'required'), + 'password' => array('text', 'required'), + 'is_admin' => array('bool'), + 'token' => array('text') + ); + + protected $hidden = array( + 'password', 'token' + ); +} +``` + +If you try to: +```php +echo $user->password; +echo $user->token; +``` + +Will return `null`, and also: +```php +$user->password = "my-new-password"; +``` + +Won't change the current `password` value. + ###Examples Please look for a use examples in tests file and test models inside the test models directory diff --git a/dbObject.php b/dbObject.php index 229dd043..ea00efee 100644 --- a/dbObject.php +++ b/dbObject.php @@ -124,6 +124,9 @@ public function __construct ($data = null) { * @return mixed */ public function __set ($name, $value) { + if (property_exists ($this, 'hidden') && array_search ($name, $this->hidden) !== false) + return; + $this->data[$name] = $value; } @@ -135,7 +138,10 @@ public function __set ($name, $value) { * @return mixed */ public function __get ($name) { - if (isset ($this->data[$name]) && $this->data[$name] instanceof dbObject) + if (property_exists ($this, 'hidden') && array_search ($name, $this->hidden) !== false) + return null; + + if (isset ($this->data[$name]) && $this->data[$name] instanceof dbObject) return $this->data[$name]; if (property_exists ($this, 'relations') && isset ($this->relations[$name])) { @@ -159,9 +165,8 @@ public function __get ($name) { } } - if (isset ($this->data[$name])) { + if (isset ($this->data[$name])) return $this->data[$name]; - } if (property_exists ($this->db, $name)) return $this->db->$name;