Dynamic Finders in CFWheels

One of the unexpected treats to using CFWheels is how much more readable it can make your code. Im not a big fan of inline comments because I believe in self-documenting code. One of the features of CFWheels that helps to achieve this is “Dynamic Finders”. Here’s a quick example:

Consider this controller:

component extends="Controller" output="false" {

	public void function incompleteTasks(){
		tasks = model('Task').findAll(where="completed = false");
	}

	public void function lastIncompleteTask(){
		task = model('Task').findOne(where="completed = false", order="createdAt DESC");
	}
}

Notice the code is pretty simple, we are retrieving a query of the tasks that are completed by passing the where attribute into our findAll() method with the condition to check for. In the second method, we are retrieving the last incomplete task by passing in the same where clause and ordering the result by the createdAt date in descending order. This is already pretty clean and I love how simple Wheels makes this stuff. But, there is a more readable way to write this using dynamic finders.

component extends="Controller" output="false" {

	public void function incompleteTasks(){
		tasks - model('Task').findAllByComplete(false);
	}

	public void function lastIncompleteTask(){
		task = model('Task').findOneByComplete(value="false", order="createdAt DESC");
	}
}

Notice how we append the column attribute to the method that we want to filter by? In my opinion this is a better example of self-documenting code as its a bit more readable.

So what if we want to filter our results by more than one column? Wheels gives us that ability as well so we still dont have to go back to manually passing a where clause.

tasks = model('Task').findAllByCompleteAndUserid('false,1');

You simply add the other column after the “And” then pass your arguments as a list item to the method. Simple right?

Just a small often over-looked feature that could help make your code just a little cleaner.

One thought on “Dynamic Finders in CFWheels”

Leave a Reply

Your email address will not be published. Required fields are marked *


*