OPV OPV - 5 months ago 30
PHP Question

Factory pattern - how to avoid switch construction?

I use simple

Factory pattern
, look at screen, please:

enter image description here

As you can see I use switch operator to choose object and create instance.

But if there are over 100 classes? Problem is came.
How to avoid switch construction? Using interface?

Answer Source

You can avoid switch or if statements by using variable with class name together with new keyword the only thing you have to care about is namespace! Your code must look like this:

$className = "YourNamespace\\SomeFactory\\SomeImplementation\\" . $type;
return new $className(new Position());

Also, you can check if class exists:

if (class_exists($className) === false) {
    throw new Exception("Class $className not found.");

and only after that create you new instance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download