I posted a question on StackOverflow and users recommended me to switch from MySQL (MariaDB) to MongoDB. After reading a lot today, I decided to install Couchbase with the PHP SDK.
Now, how should I put this in a upsert command?
Do you guys create a php class, get the $_POST variable, hydrate/populate the class with those and then generate the arrays according to the data in it?
I want to make this right so a little help would be great!
Hope it was a good place to ask this.
Another option is that your model already support JsonSerializable, which is probably already implemented in your framework, or done manually like this:
<?php
class UserAccount implements JsonSerializable
{
private $name;
private $password;
private $passwordHash;
public function __construct($attributes)
{
if (is_object($attributes) && get_class($attributes) == 'stdClass') {
$attributes = (array)$attributes;
}
$this->name = $attributes['name'];
if (isset($attributes['password_hash'])) {
$this->passwordHash = $attributes['password_hash'];
}
if (isset($attributes['password'])) {
$this->setPassword($attributes['password']);
}
}
public function getName()
{
return $this->name;
}
public function getPassword()
{
return $this->password;
}
public function setPassword(string $password)
{
$this->password = $password;
$this->passwordHash = password_hash($password, PASSWORD_BCRYPT);
}
public function getPasswordHash()
{
return $this->passwordHash;
}
public function jsonSerialize()
{
return [
'name' => $this->name,
'password_hash' => $this->passwordHash
];
}
}
$cluster = new CouchbaseCluster('couchbase://localhost');
$bucket = $cluster->openBucket('default');
$account = new UserAccount(['name' => 'arthur', 'password' => 's3cret']);
$bucket->upsert('u:arthur', $account);
$res = $bucket->get('u:arthur');
$account = new UserAccount($res->value);
var_dump($account);
//=> class UserAccount#7 (3) {
// private $name =>
// string(6) "arthur"
// private $password =>
// NULL
// private $passwordHash =>
// string(60) "$2y$10$2lMpbjaAxWztZLzIiFRPXenHA44GBVsfzOP/TIH9uCYV6bTQDNMYG"
// }
I would prefer the second option, as it structures your code better.