Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
class Role {
protected $name;
protected $permissions = [];
public function __construct(string $name, array $permissions) {
$this->name = $name;
$this->permissions = $permissions;
}
public function getName() : string {
return $this->name;
}
public function hasPermission($name) : bool {
return in_array($name, $this->permissions);
}
}
class RoleStorage {
protected $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
public function get(string $name) : Role {
return new Role(
$name,
$this->getPermissionsForRole($name)
);
}
protected function getPermissionsForRole(string $name) : array {
return $this->pdo->prepare('...your sql goes here...')
->execute([$name])
->fetchAll();
}
}
$PDO = new PDO($dsn, $user, $pass, $options);
$RoleStorage = new RoleStorage($pdo);
$foo = $RoleStorage->get('foo');
var_dump($foo->hasPermission('bar'));
@adrian-enspired
Copy link
Author

storage and entity are separate concepts.

the storage object stores+retrieves entities in the database. it knows nothing about the entity's functionality.

the entity knows about its values, what they mean and how to validated them, can answer business questions about it, and so forth. it knows nothing about the database or how it is stored when not in use.

note in this example RoleStorage is really both storage and a factory (it stores+retrieves from the db, but also creates the Role objects). This isn't completely ideal, but I don't really care that much. I'll leave this refactoring to you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment