Theory
So basically your question is: "How do I transfer a domain object from a recognition service using some kind of content service?" I really thought about this for some time.
As I see, there are 4 options. Two shit, one good and one in between:
The previously mentioned approach was factory service.
This is the most naive decision, because in a real situation you will get uncontrolled growth for the graph of objects - a service containing services that contain services. ad nauseum.
It is unstable, but fast.
Change the recognition service so that it returns an instance of Account
to the controller, which, in turn, goes to other services.
Essentially, you must create a deliberate leak between the layers to minimize complexity. You can call this "architectural denormalization."
This is a hack and poor architecture.
Use the DI container to share domain objects (and even them) between services.
This method is more complicated in the previous two, but it will also allow you to completely get rid of factories inside your services.
The best option , but requires additional skills and code.
Use the factory domain object to create an instance of Account
(and all others or selected ones) only once.
As if in this , but for domain objects. Of course, you will need some way to bypass the cache as well, because a large group of domain objects will require the ability to run several times. Thus, the need for some configuration.
A good solution halfway, but allows you to maintain a familiar API in services.
Confession
I am currently using option 2. The reason is that I do not have a DI container that I could use (and I thought about "option 4" just 5 minutes ago). Most of what you see under the description of "PHP DI container" are actually various service locators (in this case, you are still better off with a bunch of factories).
If you want to go with a DI container, my endorsement will be Auryn .
And the reason I don't use it myself, because I'm really arrogant, I want to create my own DI container.
PS
Instead of writing this:
$post->setAuthor($user);
You should write something like this:
$post->setAuthorId($user->getId());
.. for two reasons:
- You are not using an active recording. Therefore, you do not need the
Post
instance to manage its relationships with other objects. This is what you have a service for. - If you transferred the entire instance of
Account
, you will ultimately retrieve the identifier. Thus, you violate the Law of Demeter , which is not of practical use.
source share