Quantcast

Fwd: [zf-contributors] Zend\Stdlib\Options

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Fwd: [zf-contributors] Zend\Stdlib\Options

Jurian Sluiman-3
Forgot to reply to zf-contributors (damn Gmail). This is for the archive :)

---------- Forwarded message ----------
From: Jurian Sluiman <[hidden email]>
Date: 2012/6/26
Subject: Re: [zf-contributors] Zend\Stdlib\Options
To: Gary Hockin <[hidden email]>


2012/6/26 Gary Hockin <[hidden email]>
Hello,

I understand that constructor options should now be using the Zend\Stdlib\Options class, I'm a little bit confused as how this should work.

Say I'm working on creating a Hello World class, and I've already defined the Options class as HelloWorldOptions, how do I pass default options in the constructor to HelloWorld? Do I pass as an array and HelloWorld then creates a HelloWorldOptions class from that array, or am I expected to pass a HelloWorldOptions class myself? 

As far as I understand, you have two options:

1. Instantiate the options class yourself, pass it on to the constructor
2. Use an array of options, the constructor would instantiate the options class

It would look like this:

public function __construct($options = aray())
{
  if (is_array($options)) {
    $options = new HelloWorldOptions($options);
  } elseif (!$options instanceof HelloWorldOptions) {
    throw new InvalidArgumentException('Options parameter $options must be an array or instance of HelloWorldOptions');
  }

  $this->options = $options;
}

Now you can either:

$foo = new HelloWorld(array( ... ));

Or:
$options = new HelloWorldOptions(array(....));
$foo = new HelloWorld($options);

Or:
$options = new HelloWorldOptions;
$options->setBar($bar);
$foo = new HelloWorld($options);


Secondly, if I want to change an option at runtime, how is that handled? Does HelloWorld proxy it's HelloWorldOptions class so I can access the setter defined there in the format:

$helloWorld->options->setWorldName('earth');

Or should HelloWorld create it's own setters that allow me to change options. If the latter is true, should setWorldName exist in both HelloWorld and HelloWorldOptions?


I would not copy over all accessors and mutators from the options class to the functional class. That's just a waste of developing time and resources. You can create an options getter:

$helloWorld->options()->setFoo($bar);

I would suggest not to use a public property, as you could externally modify the options class (set it to a FooBar instance) and this will break the HelloWorld class. An options() or getOptions() method seems more appropriate.
-- 
Jurian Sluiman



--
Balthasar vd Polweg 56 | 2628 AW Delft | +31 6 41 79 39 69
http://juriansluiman.nl | [hidden email] | twitter.com/juriansluiman

Loading...