I have a class called Sharer
, which accepts a Service
interface in the construct method. Service
can be FacebookService
or TwitterService
and so on. Each Service
class has a post
method, that posts whatever array data you pass to that method, using its own connection (either facebook, twitter in this example).
Now the Sharer
class normalizes
data before sending it to that service
's post method. By normalizing, it checks whether the thing we are sending to that post
method is just a simple array or a Model
class. Model
can be either Project
model, or Image
model, or Video
model and so on.
If it is a model class, then it calls that specific model's transformer. Transformers
are just helper classes, that accept the model instance and they have two methods - facebook
and twitter
in this case. And each method returns a formatted array, specific to the connection.
So for example, facebook
method grabs the required fields (that are needed to post on facebook) from the model and sends that array back. And twitter method does the same for twitter's required fields.
Now the thing I am a bit stuck with, is calling that specific method on the transformer class. I want to do something like this:
if(we are sharing on facebook) {
then call the facebook method
}
if(we are sharing on twitter) {
then call the twitter method
}
but obviously I want to somehow make it dynamic and not have these if statements. What would be a better approach to this?
I solved it doing this:
$method = $this->resolveMethodToCall();
protected function resolveMethodToCall()
{
$reflection = new ReflectionClass($this->service); // service being either a FacebookService class or TwitterService
$shortName = $reflection->getShortName();
return strtolower(str_replace('Service', '', $shortName));
}
Probably not the best solution, but works well and after this I am checking if the resolved method actually exists on the transformer class and throw an exception if it doesn't.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.