I have no idea if I'm doing this efficiently, or ideally, but I've written what I think is a factory. Please help me understand if this is good practice, or if there is another direction I should take this. There's no particular project in mind with this, I'm just farting around. (Written in PHP)
class Factory
{
private function __construct(){}
/**
* @param $obj Object to Create.
* @param $params Params (use array for multiple parameters) to be passed.
*/
public static function build($obj, $params=null) {
switch ($obj) {
case 'db': return new DB($params);
default: return null;
}
}
}
This lets me do something like $db = Factory::build("db","test_database_name");
The DB class just builds a PDO connection using appropriate parameters based on the database I'm trying to access, which is useful for me because I deal with MySQL and MS SQL all day long, and I don't want to have to remember all the connection strings, users, and passwords (stored in the DB class). That's kind of besides the point, I just intend this to be expanded as I develop more useful classes, so...
I just want to get some opinions on the the topic of a Factory. Is this a good method? are there others that are considered superior? If so, what have I overlooked?
-
\$\begingroup\$ Is Wouter J the only one with any input on this? \$\endgroup\$jdstankosky– jdstankosky2013年03月21日 12:43:51 +00:00Commented Mar 21, 2013 at 12:43
1 Answer 1
In my opinion, a factory should create a specific class, global ones like this one shouldn't be used. For instance, having a PizzaFactory is something like this:
class PizzaFactory
{
public static function createPizza($type)
{
switch ($type) {
case 'salami':
return new SalamiPizza();
break;
case 'hawai':
return new HawaiPizza();
break;
}
}
}
I just want to get some opinions on the the topic of a Factory. Is this a good method? are there others that are considered superior? If so, what have I overlooked?
An upcomming design pattern is depedency-injection. Just search for some resoures about that and keep reading. It is used in all modern frameworks (ZF2 and Symfony 2 uses it).
See also this article serie by Fabien Potencier: "What is Dependency Injection?"
-
\$\begingroup\$ I'd actually agree with the factories building a specific type of thing. The DB class was the only one I had written thus far, although I could use it directly as
$db = new DB("db_name");
to connect to any of my many databases... This Dependency Injection stuff kinda seems (at first glance) like regular factories (as I envision them), but backwards. All it is, is passing objects as parameters into other objects? \$\endgroup\$jdstankosky– jdstankosky2013年03月13日 15:53:10 +00:00Commented Mar 13, 2013 at 15:53