Answer the question
In order to leave comments, you need to log in
PHP: One object can be created from many others, where is the right place to place factories?
Initial disposition: there are objects of type Video that can be created and initialized with some kind of logic by objects of other types News, Post, Episode - these objects are not related to each other. The question is how to properly distribute factories between classes?
Option 1:
Class News {
public function createVideo() {
$video = new Video;
$video->title = $this->title;
$video->picture_id = $this->picture_id;
$video->save();
$link = new News_Video;
$link->news_id = $this->id;
$link->video_id = $video->id;
$link->save();
return $video;
}
}
Class Post {
public function createVideo() {
//
}
}
Class Episode {
public function createVideo() {
//
}
}
$news = NewsStorage::find(1);
$video = $news->createVideo();
Class Video {
static public function createFromNews( News $news ) {
$video = new self;
$video->title = $news->title;
$video->picture_id = $news->picture_id;
$video->save();
$link = new News_Video;
$link->news_id = $news->id;
$link->video_id = $news->id;
$link->save();
return $video;
}
static public function createFromPost( Post $post ) {
//
}
static public function createFromEpisode( Episode $episode ) {
//
}
}
$news = NewsStorage::find(1);
$video = Video::createFromNews($news);
Answer the question
In order to leave comments, you need to log in
This is a purely technical issue. In the second option, your method is not bound to the class(es). In the first one, you have a reference to $this, so it's already OOP. The code from the first example will be easier to understand in a year.
As far as I understand, Video has a certain number of fields that are filled regardless of the type of object (News, Post or Episode). If this is the case, then it is enough just to make sure that the classes have the same field names (title, picture_id) required to create an object of the Video type. This can be done, for example, using an abstract class or an interface.
It will come out something like this:
Class News {
public function createVideo($entity) {
$video = new Video;
$video->title = $entity->title;
$video->picture_id = $entity->picture_id;
$video->save();
$link = new News_Video;
$link->news_id = $this->id;
$link->video_id = $video->id;
$link->save();
return $video;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question