Skip to content

Instantly share code, notes, and snippets.

@jedateach
Created April 3, 2012 03:25
Show Gist options
  • Save jedateach/2289055 to your computer and use it in GitHub Desktop.
Save jedateach/2289055 to your computer and use it in GitHub Desktop.
Planning new ShoppingCart system
<?php
/*
* goal: build SQL filter, based on parameter array
*/
//a hypothetical filter(parameters) for a new order item.
//This data would typically come from request parameters.
$filter = array(
'Size' => 20,
'Color' => 'blue',
'Premium' => true,
'Date' => '2-3-2014',
'RelatedObject' => 35
);
//I could even introduce an extra callback to do more complex duplicate checks
//eg: date falls within a particular week, or size is between x and y
//this might come from OrderItem::$allowed_fields;
//this would prevent
$allowed_fields = array(
'Size',
'Color',
'Premium',
'Date'
);
foreach($filter as $key => $value){
if(!in_array($key,$allowed_fields)){
unset($filter[$key]); //remove non allowed fields
}else{
$filter[$key] = Convert::raw2sql($value);
}
}
//TODO: automatically add in any other missing allowed fields as empty/null query
//otherwise you might get a result that you shouldn't
//eg a red sweater is not the same as a sweater
$filter['ProductID'] = $product->ID;
$filter['OrderID'] = $order->ID;
//add query to
$result = DataObject::get_one('OrderItem',$filter);
@jedateach
Copy link
Author

I thought the same thing might be able to be accomplished with SearchContext. I'm not so sure after trying, as I think it relates too much to searching from a form, rather than a generic array.

@sunnysideup
Copy link

interesting concept. Can you pass an array to DataObject::get_one - is that possible or is this just shorthand?

@jedateach
Copy link
Author

I believe you can. See SQLQuery ->where function, which is the code DataObject::get uses for filtering.

EDIT: after things failing for a bit, I found it isn't / shouldn't be possible. ie, don't bother trying.

@jedateach
Copy link
Author

I think I may need ensure data is correctly formatted by passing each through appropriate DBField ->setValue. However, I can't see this happening in SearchContext, which is performing a similar role.

@jedateach
Copy link
Author

I've posted my updated (mostly working) idea here: https://gist.github.com/2395385

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment