I am a little bit confused by chosing the right design pattern for my problem. Here is my code:
<?php
class Report_Journal ...
class Report_Recommendation ...
class Report_Customer ...
$type = "journal"; // value can also be "recommendation or customer"
?>
Now I want to create the correct object for that specific type, means in that case Report_Journal. I was thinking of the factory pattern, but what I do not like about a factory are its dependencies that are not injected but defined inside the class. How would you solve the problem? Thanks in advance.
BR, Chris
The factory pattern is from my point of view the correct approach. You should create an interface
in the first place to define the common interface of all those types and use that to put in your parameter list of all those methods using that classes.
function blub(myInterface $obj)
that is explicitly needed for depency injection, imagine the blub
method is used to inject the needed class. Since all your three objects inherit from myInterface
the method blub
applies for all of them.
Finally you can create a factory method like
function getInstance($objectType, $params){
if (!class_exists($objectType)) {
throw new Exception('Bad type');
}
$instance = new $objectType($params);
return $instance;
}
for a deeper look (based on php) you can have a look into that blog post
http://net.tutsplus.com/tutorials/php/understanding-and-applying-polymorphism-in-php/