M
M
magary42016-09-21 17:07:46
symfony
magary4, 2016-09-21 17:07:46

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

2 answer(s)
S
Stepan Pyzhov, 2016-09-25
@turintomsk

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']);
    }
}

S
Sergey, 2016-09-21
Protko @Fesor

like return new Post($searchResult) ?

php.net/manual/en/reflectionclass.newinstancewitho...
What you have to write is called hydrators. They take a state and push it into an object bypassing methods (directly by mapping). The alternative is to make a static constructor method that will do all the same but almost without reflections. The third option is proxy classes (that's how the doctrine does it).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question