Skip to content

Instantly share code, notes, and snippets.

@thepsion5
Last active August 23, 2019 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thepsion5/03fd4b5fb2afd52a97d7bb093c5cc1f5 to your computer and use it in GitHub Desktop.
Save thepsion5/03fd4b5fb2afd52a97d7bb093c5cc1f5 to your computer and use it in GitHub Desktop.
Example of a PHP class that stores dynamic properties in an array
<?php
$db = new PDO(/* some database credentials */);
$someUserData = [
'email' => 'example@example.com',
'user' => 'Example'
];
$user = new User($someUserData);
$user->active = true;
$user->admin = false;
$sqlParams = [];
$insertSql = $user->getInsertSqlStatement('users', $sqlParams);
// INSERT INTO `users`(email, user, active, admin)
// VALUES(:email, :user, :active, :admin);
$statement = $pdo->prepare($insertSql);
$statement->execute($sqlParams);
<?php
/**
* Example of a PHP class that stores dynamic properties in an array, and then can be used to create a SQL statement
*
* I would consider this a proof-of-concept and I do not believe this is a good practice
*/
class User
{
/**
* @var array Object attributes
*/
private $attrs = [];
public function __construct(array $attributes = [])
{
$this->attrs = $attributes;
}
public function __get(string $attrName)
{
return $this->attrs[$attrName] ?? null;
}
public function __set(string $attrName, $attrValue): void
{
$this->attrs[$attrName] = $attrValue;
}
/**
* Returns the array of object attributes
*
* @return array
*/
public function getAttrs(): array
{
return $this->attrs;
}
/**
* Generates an insert SQL statement using the attribute keys as column names
*
* @param string $tableName The name of the table for which the insert statement is being created
* @param array $parameters An array of parameters that will be filled from the object attributes
* @return string The completed SQL statement
*/
public function getInsertSqlStatement(string $tableName, array &$parameters): string
{
foreach($this->attrs as $attrKey => $attrValue) {
$placeholder = preg_replace('@\W@', '_', $attrKey);
$parameters[$placeholder] = $attrValue;
}
$columnNames = '`' . implode('`, `', array_keys($this->attrs)) . '`';
$placeholders = ':' . implode(', :', array_keys($parameters));
$sql = <<<SQL
INSERT INTO `$tableName` ($columnNames)
VALUES ($placeholders)
SQL;
return $sql;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment