Note that there are some explanatory texts on larger screens.

plurals
  1. POFactory class with object initialization - trying to avoid static
    text
    copied!<p>I'm trying to design a set of factory classes for our system, where some objects created by the factory also need to be initialized before they can be used properly.</p> <p>Example:</p> <pre><code>$foobar = new Foobar(); $foobar-&gt;init( $qux, ... ); // $foobar ready for usage </code></pre> <p>For the same of example, lets say that the <code>$qux</code> object is the only dependency that <code>Foobar</code> needs. What I'd like to get to is:</p> <pre><code>$foobar = Foo_Factory( 'bar' ); </code></pre> <p>In order to avoid the need to pass along the <code>$qux</code> object across the whole system and pass it to the factory class as another parameter, I'd like to perform initialization of <code>Foobar</code> directly in the factory class:</p> <pre><code>class Foo_Factory { public static function getFoo( $type ) { // some processing here $foo_name = 'Foo' . $type; $foo = new $foo_name(); $foo-&gt;init( $qux ); return $foo; } } </code></pre> <p>There are few solutions that come to mind, but none of them is ideal:</p> <ol> <li>Add a static setter method for <code>$qux</code> to the factory class, and let it store a reference to <code>$qux</code> in a private static variable. The system can set <code>$qux</code> at the start, and the factory class can prevent any future changes (for security reasons).<br />Although this approach works, using a static parameter for storing reference to <code>$qux</code> is problematic during unit testing (e.g. it happily lives survives between individual tests due to its static state).</li> <li>Create a new context class using Singleton pattern and let the factory class use it to get a reference to <code>$qux</code>. This might be a bit cleaner way to do this than option #1 (although we move the static problem from the factory class to the context class).</li> <li>Use dependency injection all the way, i.e. pass <code>$qux</code> to any object which uses the factory class, and let that object pass it along to the factory class as another parameter: <code>Foo_Factory::getFoo($type, $qux);</code>.</li> <li>Same as above (#3), but instead of passing <code>$qux</code> along the system, pass an instance of the factory class instead (i.e. in this case it would not be static, but instantiable).</li> </ol> <p>What would you recommend please? Any of the four alternatives mentioned above, or is there a better way to do this please?</p> <p>Note: I don't want to get into a <code>static is evil</code> flamewar here, just trying to come up with the best solution.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload