Answer the question
In order to leave comments, you need to log in
How to correctly pass an object to a class and is it worth it?
Hello!
I have a Posts class that works with a database (more precisely, with a table of posts and related tables).
From the outside, I request data.
The class receives data from the database, creates PostEntity objects based on the received data, and returns it to the calling class.
The PostEntity object is a class containing setters and getters with the simplest data manipulations. It also implements the JsonSerializable interface which allows me to simply throw an object into the JSON output and pass it to the application. To the question:
The post object has a PostEntity->getText() methodPosts->getById(33);
which gives data with html tags. But now I have a need to make it so that in different places of the API I can specify in what format I should give the text of the post (with html tags or BB codes).
Because the file that calls the method does not interact in any way, and should not interact with the PostEntity object , I can’t influence the PostEntity->getText() method in any way , because I don’t call it, because the data is output by implementing the JsonSerializable method .
How to solve this problem?
I have an idea that when calling a method I should pass the path to a new object, for example, PostEntityBBCodes , which will extend the PostEntity classPosts->getById(33);
Posts->getById(33);
and override the getText() method so that it converts the data not to HTML but to BB codes.
Am I doing the right thing in this case?
And it's still not entirely clear how to pass an object to the Posts class , because if I need to get several posts. Then each subsequent post will overwrite the object of the previous one. because objects are passed by reference.
Answer the question
In order to leave comments, you need to log in
But now I have a need to make it so that in different places of the API I can specify in what format I should give the text of the post (with html tags or BB codes).
echo $bbFormatter->format($html); // $html - $entity->getText()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question