Answer the question
In order to leave comments, you need to log in
Repository for DB lookup?
There is a client that makes a selection from the database .
There is an object, Post
. And there is a repository class containing methods; getPostById, getPost s ByTitle
The call of which should return an object of type Post or an array of Post,
the repository builds Query and passes it to the database client and receives the result of the query, what should happen next? do I have to do something like return new Post($searchResult) ? to transfer crude result of selection from a DB to the constructor of object?
or how PS
do it .
Requirements that it should all work without doctrine.
Answer the question
In order to leave comments, you need to log in
By default, for such cases, a class (model) is implemented with a complete list of parameters for the constructor (possibly with default parameters) and a method that creates this object.
class Post {
private $id;
private $title;
private $description;
/** ... etc ... */
public function __construct($id, $title, $description) {
$this->id = $id;
$this->title = $title;
$this->description = $description;
}
public function getId() {
return $this->id;
}
public function getTitle() {
return $this->title;
}
public function getDescription() {
return $this->description;
}
}
class PostProvider {
public function getPostById($id) {
$response = /** ... Получаем данные ... */;
if (!$response) {
throw new Exception('Not found.');
}
return $this->createPost($response);
}
public function getPostsByTitle($id) {
$result = [];
$responses = /** ... Получаем данные ... */;
foreach ($responses as $response) {
$result[] = $this->createPost($response);
}
return $result;
}
/**
* Метод возвращает объект Post по переданному массиву данных
* @return Post
*/
private function createPost(array $response){
return new Post($response['id'], $response['title'], $response['description']);
}
}
like return new Post($searchResult) ?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question