Inside a ColdFusion component I declare a function like this:
string function render(required Array actions) output=false {
//...
}
So the function parameter can only accept an Array. However, I need to make sure the array contains only "ActionItem" objects (there is an ActionItem.cfc component)
Is there a way in ColdFusion to type-hint the array contents? What solution do you suggest in this case?
In short, as Peter has said in his comment, the basic answer is "you can't". ColdFusion doesn't have the notion of typeful arrays.
There's two ways around this. Firstly the brute-force approach of validating each array item as you need it, making sure it's the type you need. This is what Peter suggests, and generally what I'd do.
Failing that you could implement an ActionItemCollection.cfc
which itself contains an array of ActionItems
, and leave it to ActionItemCollection.cfc
to only accept ActionItem
objects, so by the time your render()
function receives its ActionItemCollection
argument, it "knows" each element in the collection is definitely an ActionItem
.
That said, that's perhaps an awful lot of work when you could just get render()
to check if the element is legit, and throw an exception if not. It's not a perfect solution, but CF is creating an imperfect situation, so fair enough.
To elaborate on my comment, the following is an outline of a possible collection you could create.
I love collection classes and the ArrayCollection
class here is very reusable and allows you to use the wrapped array as an object.
component ArrayCollection()
{
public function init()
{
variables.collection = [];
return this;
}
public any function get();
public function set(required array collection);
public function add(required any item);
public function remove();
}
component ActionItemCollection extends ArrayCollection
{
public function add(required ActionItem item);
public ActionItem function get();
}
component otherComponnet{
public string function render(required ActionItemCollection actions)
{
}
}
It my be overkill in some circumstances, however it allows you to enfore the type of items within the array!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With