Dynamic Finders
Make your model calls more readable by using dynamic finders.
Since the introduction of
onMissingMethod()
in CFML, we have been able to port over the concept of dynamic findersfrom Rails to CFWheels.The concept is simple. Instead of using arguments to tell CFWheels what you want to do, you can use a dynamically-named method.
For example, the following code:
me = model("user").findOne(where="email='[email protected]'");
Can also be written as:
me = model("user").findOneByEmail("[email protected]");
Through the power of
onMissingMethod()
, CFWheels will parse the method name and figure out that the value supplied is supposed to be matched against the email
column.You can take this one step further by using code such as:
me = model("user").findOneByUserNameAndPassword("bob,pass");
In this case, CFWheels will split the function name on the And part and determine that you want to find the record where the username column is "bob" and the password column is "pass".
When you are passing in two values, make special note of the fact that they should be passed in as a list to one argument and not as two separate arguments.
The below code, for example, is perfectly valid:
users = model("user").findAllByState(value="NY", order="name", page=3);
When passing in multiple arguments like above, you have to start naming them instead of relying on the order of the arguments though. When doing so, you need to name the argument
value
if you're passing in just one value and values
if you're passing in multiple values in a list. In other words, you need to name it values
when calling an And
type dynamic finder.users = model("user").findAllByCityAndState(
values="Buffalo,NY", order="name", page=3
);
Keep in mind that this dynamic method calling will break down completely if you ever name a column
firstandlastname
or something similar because CFWheels will then split the method name incorrectly. So avoid using "And" in the column name if you plan on taking advantage of dynamically-named finder methods.