Skip to content

Instantly share code, notes, and snippets.

@adrian-enspired
Created July 14, 2018 00:59
Show Gist options
  • Save adrian-enspired/4c99eb513d1f6dcd39789f5e17df56eb to your computer and use it in GitHub Desktop.
Save adrian-enspired/4c99eb513d1f6dcd39789f5e17df56eb to your computer and use it in GitHub Desktop.
<?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