[Flow] getters for option arrays (Surf)

Martin Kutschker masi-20l4 at typo3.org
Sun Nov 2 18:24:29 CET 2014


Am 02.11.2014 16:50, schrieb Helmut Hummel:> Hi Martin!
 >
 > On 02.11.14 14:47, Martin Kutschker wrote:
 >
 >> public function getOption($key) {
 >>     return $this->options[$key];
 >> }
 >>
 >> If you ask for an option that has not been set, PHP will issue a notice
 >> which in turn be changed by Flow into an exception. I know I can fiddle
 >> around with the PHP configs (and Flow configs?), but shouldn't be the
 >> code changed to avoid this?
 >
 >  From what I know from the Surf code, this is on purpose!
 >
 >> A  simple solution:
 >>
 >> public function getOption($key) {
 >>     return isset ($this->options[$key]) ? $this->options[$key] : NULL;
 >> }
 >
 > Instead, the code that evaluates the options should decide if an option
 > is required or not.

Node has a hasOption() method. Though the code is a bit quirky IMHO 
because internally the hostname is part of the options array yet there 
are setters and getters for the hostname.

Note that the getHostname() method will also thrown an exception 
triggered by the PHP notice as it is simply a wrapper around getOption().

 > But in any case this is better to throw an exepction instead of
 > proceeding and accidently using a NULL value which could lead to
 > unexpected results.

How to fix the issue?

a) Initialize the not-so-optional hostname option with an empty string 
or 'localhost'.

b) Add an optional parameter to the constructor defaulting to ''.

c) Fix getHostname() to raise a more meaningful exception by calling 
hasOption() first.

I'm not so fond of getters that throw exceptions. It will lead to 
try/catch-blocks all over the place.

Masi

Reference:

protected $options = array();

public function getHostname() {
   return $this->getOption('hostname');
}

public function getOption($key) {
     return $this->options[$key];
}



More information about the Flow mailing list