Answer the question
In order to leave comments, you need to log in
How to properly organize classes?
I am mastering the features of php that I have not used before, having moved from php 5.2 to php 5.6 along the way, I learned about PSR-0,1,2,4 by stumbling upon this (PHP Right Way) document.
Here I set the task: to implement the ability to work with different types of storages (git, mercurial).
I make a package in which I implement:
Answer the question
In order to leave comments, you need to log in
I use this approach:
There are three interfaces EntityInterface, RepositoryInterface, RepositoryDriverInterface
interface EntityInterface extends Serializable {
public function getId();
}
interface RepositoryInterface {
public function getDriver();
public function findById($id, EntityInterface $Entity);
public function save(EntityInterface $Entity);
}
interface RepositoryDriverInterface {
public function set($id, $data);
public function get($id);
}
class RepositoryDriverArray implements RepositoryDriverInterface {
private $data = [];
public function set($id, $data) {
$this->data[$id] = $data;
}
public function get($id) {
return $this->data[$id];
}
}
class RepositoryDriverRedis implements RepositoryDriverInterface {
protected $Redis = null;
public function __construct(Client $Redis) {
$this->Redis = $Redis;
}
public function set($id, $data) {
$jsonData = json_encode($data);
$this->Redis->hset($this->getContainerName(), $id, $jsonData);
}
public function get($id) {
$jsonData = $this->Redis->hget($this->getContainerName(), $id);
$data = json_decode($jsonData, true);
return $data;
}
public function getContainerName() {
return 'myContainer';
}
}
abstract class AbstractRepository implements RepositoryInterface {
protected $RepositoryDriver = null;
public function __construct(RepositoryDriverInterface $RepositoryDriver) {
$this->RepositoryDriver = $RepositoryDriver;
}
public function save(EntityInterface $Entity) {
$this->getDriver()->set($Entity->getId(), $Entity->serialize());
}
public function findById($id, EntityInterface $Entity) {
$data = $this->getDriver()->get($id);
$Entity->unserialize($data);
return $Entity;
}
public function getDriver() {
return $this->RepositoryDriver;
}
}
class User implements EntityInterface {
// TODO: Implement methods
}
class UserRepository extends AbstractRepository {}
$Redis = new Client([/* connection params */]);
$RedisDriver = new RepositoryDriverRedis($Redis);
$UserRepository = new UserRepository($RedisDriver);
$User = new User();
$UserRepository->save($User);
$User = new User();
$UserRepository->findById(1, $User);
$ArrayDriver = new RepositoryDriverArray();
$UserRepository = new UserRepository($ArrayDriver);
$User = new User();
$UserRepository->save($User);
$User = new User();
$UserRepository->findById(1, $User);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question