A method to make named parameters strongly defined.

Added a method that processes named parameters and ensures all mandatory ones
exist and substitutes missing optional ones with default values.  This makes
named parameters strongly defined and easier to read.

Thanks to http://developinginthedark.com/posts/cakephp-tip-1-named-parameters
for the idea.
This commit is contained in:
Kyle Johnson 2013-05-29 07:37:00 -04:00
parent c408575075
commit 545826b55c
1 changed files with 22 additions and 1 deletions

View File

@ -32,7 +32,7 @@ App::uses('Controller', 'Controller');
* @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
*/
class AppController extends Controller {
public $helpers = array('Html', 'Form', 'Js' => array('Jquery'));
public $helpers = array('Html', 'Form');
public $components = array('Cookie', 'Session');
public function beforeFilter() {
@ -64,4 +64,25 @@ class AppController extends Controller {
$this->set('daemonStatus', ('Stopped'));
}
}
function extractNamedParams($mandatory, $optional = array()) {
$params = $this->params['named'];
if(empty($params)) {
return false;
}
$mandatory = array_flip($mandatory);
$all_named_keys = array_merge($mandatory, $optional);
$valid = array_intersect_key($params, $all_named_keys);
$output = array_merge($optional, $valid);
$diff = array_diff_key($all_named_keys, $output);
if (empty($diff)) {
return $output;
} else {
return false;
}
}
}