samedi 19 mars 2016

Program to an interface and the Observer Pattern

First, a small introduction, to help you understand where I'm coming from: I was not sure how to title this question, either like it is, or as Repository tracking changes of the Unit of Work.

I have two interfaces, ChangeListener and ChangeSubject, which are coupled:

interface ChangeListener
{
    public function onSubjectChanged(ChangeSubject $subject, array $data);
}
interface ChangeSubject
{
    public function addChangeListener(ChangeListener $listener);
}

and I also have a repository and a unit of work (WIP, I'll leave out some parts):

interface UnitOfWork extends ChangeSubject
{
    public function commit();
    public function hydrateChange(array $data, ArrayService $arrayService);
}

interface Repository extends ChangeListener
{
    public function commit() : \bool;
    public function commitCount() : \int;
}

Now, in my implementation of the UnitOfWork, let's call it Book, more precisely in the method hydrateChange, I notify the repository of the change, which is easy:

$repository->onSubjectChanged($this, $newHydration);

The problem is now that, within the repository, I need to know the book's id. But the repository's handling method receives a ChangeSubject, which does not have an id (which the Book has).

How to properly design such a system?

If PHP had generics, it would have been possible. A hacky solution, which I don't like, is using instanceof.

enter image description here

Aucun commentaire:

Enregistrer un commentaire