Skip to content

Instantly share code, notes, and snippets.

@anoxic
Last active December 20, 2015 01:29
Show Gist options
  • Save anoxic/6049039 to your computer and use it in GitHub Desktop.
Save anoxic/6049039 to your computer and use it in GitHub Desktop.
Missing validation and database access
<?php
/**
* User class
*
* @todo Add database access and validation
*/
class User
{
/**
* A holder for all of the data
*/
private $data = array();
/**
* Arrays containing settable and gettable properties
*/
private $settable_properties = array('id', 'firstname', 'lastname', 'role', 'password', 'logins', 'pages', 'addresses');
private $gettable_properties = array('id', 'name', 'firstname', 'lastname', 'role', 'logins', 'pages', 'addresses');
/**
* Constructor that accepts an array to set values swiftly.
*/
public function __construct(array $ary = array())
{
foreach ($ary as $name => $value) {
$this->$name = $value;
}
}
/**
* Generic setter with only values in $settable_properties allowed to be set.
*
* For other values, use $this->data[$name] whithin this object
*/
public function __set($name, $value)
{
if (!in_array($name, $this->settable_properties)) {
return false;
}
$this->data[$name] = $value;
if ($name == 'firstname' || $name == 'lastname') {
$this->data['name'] = $this->firstname . ' ' . $this->lastname;
}
return true;
}
/**
* Generic getter allowing you to fetch only properties in $gettable_properties.
*
* Other properties can only be gotten from within this object.
*/
public function __get($name)
{
if (!in_array($name, $this->gettable_properties)) {
return false;
}
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
return false;
}
}
<?php
$user = new User();
$user->lastname = 'Henry';
$user->firstname = 'John';
$user->role = 'author';
$user->logins = array('john@thehenrys.com','oldjohn');
$user = new User(array('firstname' => 'John',
'lastname' => 'Henry',
'role' => 'author',
'logins' => array('john@thehenrys.com','oldjohn')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment