How to make a successful Factory Domain object in PHP

I was messing around with MVC infrastructure and I came across a problem, I'm not sure how to solve it.

I want to create a DomainObjectFactory for the Model layer of my application, however, each Domain object will have a different set of arguments, for example:

  • Person - $ id, $ name, $ age.
  • Post - $ id, $ author, $ title, $ content, $ comments
  • Comment - $ id, $ author, $ content

Etc. How can I easily tell the factory which objects I need?

I came up with several options:

  • Pass an array - I don’t like it because you cannot rely on a contract constructor to tell you what it takes to work.
  • Make the DomainObjectFactory interface and create specific classes - Problem, because it is an awful lot of factories!
  • Use Reflection - service locator? I don’t know, it seems to me that this is so.

Is there a useful deign scheme that I can use here? Or some other smart solution?

+3
source share
1 answer

Why do you want to initialize a Domain Object with all assigned properties?

Instead, just create an empty domain object. You can check the factory if it has a prepare() method to execute. Oh .. and if you use DAO , instead of directly interacting with Mappers , you can create and enter the corresponding DAO in your domain object.

Assignment of values ​​should occur only in Service . Using regular setters.

Some examples:

Retrieving an Existing Article

 public function retrieveArticle( $id ) { $mapper = $this->mapperFactory->create('Article'); $article = $this->domainFactory->create('Article'); $article->setId( $id ); $mapper->fetch( $article ); $this->currentArticle = $article; } 

Posting a new comment

 public function addComment( $id, $content ) { $mapper = $this->mapperFactory->create('article'); $article = $this->domainFactory->create('Article'); $comment = $this->domainFactory->create('Comment'); $comment->setContent( $content ); $comment->setAuthor( /* user object that you retrieved from Recognition service */ ); $article->setId( $id ); $article->addComment( $comment ); // or you might retrieve the ID of currently view article // and assign it .. depends how you build it all $mapper->store( $article ); // or } 

Passing User Input

 public function getArticle( $request ) { $library = $this->serviceFactory->build('Library'); $library->retrieveArticle( $request->getParameter('articleId')); } 
+3
source

Source: https://habr.com/ru/post/916223/


All Articles