Reputation: 343
I am using CodeIgnitor and I have a class with an array defined that has default settings but I want to be able to call one of the functions and replace one or more of the Array values, like this:
In a Model I have:
class Search {
var $items = array("limit" => 10, "query"=>"foobars");
function dosearch($items) {
...
}
}
then call it from a Controller...
$this->load->model('search_model');
$items = array("limit"=>100);
$this->search_model->dosearch($items);
To be clear I just want to override some of the Models Class Array values and leave the rest as they are.
How can I best do this?
Thanks.
Upvotes: 0
Views: 306
Reputation: 343
OK, I worked out a really elegant solution that works for CodeIgnitor.
Create a config file, let's call it defaultdata.php and add your default data.
$config['searchData'] = array("limit"=>10, "query"=>"foobar");
then in your Controller add:
$this->config->load('defaultdata');
$this->load->model('dostuff_model');
$temp = $this->config->item('searchData');
$temp["limit"] = 100;
$data = $this->dostuff_model->search($temp);
...
and then you have the full array modified for this call ready to go! BOOM!!!!!
Thanks for your replies above guys, it helped me think this through.
Upvotes: 0
Reputation: 42925
I guess this is what you are looking for:
Extend your method implementation like this:
class Search {
var $items = array("limit" => 10, "query"=>"foobars");
function dosearch($override=array()) {
// maybe first some general plausibility checks inside $override...
if ( ! is_array($override) )
return FALSE; // better to throw an exception here!
// make a copy of $this->items you can modify:
$innerItems = $this->items;
// then use values inside $override
foreach ($override as $key=>value) {
// then some specialized plausibility checks, for example:
if ( ! in_array($key, array('limit','query') )
continue;
// is 'limit' a valid integer inside the range ]0,100]?
if ( ('limit'==$key) && (0<(int)$value) && (100>=(int)$value) )
$value=(int)$value;
else
continue;
// all fine, use override value
$innerItems[$key] = $value;
}
// now do whatever you want with $innerItems
// ...
}
}
Then you can do this at runtime:
$this->load->model('search_model');
$items = array("limit"=>100);
$this->search_model->dosearch($items);
Note that I did not test this, just wrote it down. I hope there is no minor typo left in it ;-)
Upvotes: 1
Reputation: 9689
You want to replace the $this->items
array with a new one or just change a key's value? In your example you're changing the whole array. If you wanna just change just one key, then do this $this->items['limit'] = 100
.
Upvotes: 0