Configuring an extension

The PHP runtime allows an extension to load configuration information that is stored in php.ini. This tutorial shows how to get configuration information at runtime. It extends the big decimal extension by adding a new extension function that does division of BigDecimal values.

1. Add the following Java™ code to the BigDecimalExtension class:

private int roundingMode = BigDecimal.ROUND_UP;
public void initExtension(RuntimeServices runtimeServices) {
        super.initExtension(runtimeServices);
        ConfigurationService config = runtimeServices.getConfigurationService();
        Integer propertyMode = config.getIntegerProperty(null, "rounding_mode");
        if (propertyMode != null) {
                this.roundingMode = propertyMode;
        }
}
@XAPIFunction("divide_bigdecimal")
public void divide(RuntimeContext ctxt) {
        BigDecimal arg1 = new BigDecimal(ctxt. 
        getStringArgument(0).getString());
        BigDecimal arg2 = new BigDecimal(ctxt. 
        getStringArgument(1).getString());
        BigDecimal result = arg1.divide(arg2, this.roundingMode);
        ctxt.setReturnValue(result.toString());
}

2. Change the sample.php code to exercise the new function.

<?php    
$arg0 = '111111111111111';
$arg1 = '222222222222222';
$result = divide_bigdecimal($arg0, $arg1);
echo 'The answer is: '.$result.'<br>';
?>

3. Run the IBM® WebSphere® sMash application and point a Web browser at http://localhost:8080/sample.php. This yields the result 1 since the division rounds up away from zero.

4. Now edit php.ini and set a rounding configuration setting of rounding_mode=1 and run sample.php again. The result is now 0.

The example uses the ConfigurationService interface to query the runtime for settings in php.ini.

Version 1.1.30763