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:
parent
c408575075
commit
545826b55c
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue