So, I'm trying to learn and utilize components to make my code better...
I understand what getters and setters are...however, I'm not sure where to put them in respect to how my component works. My component is a faculty which has a unique id and department. I want all my information in a struct form because each faculty has a lot of information. My init method would initialize the id and the department of the specific instance and then proceed to call a query that will populate the rest of the information into a struct. I'm just not sure how to do the getters and开发者_高级运维 setters for the id and department...do I just init a "blank" instance and then use a getter/ setter to actually do the input?
Also another thought/ question regarding components: Should my component only have methods that deal with single entities (individuals) or can I also have methods in my component that deals with the whole (like a search function for all individuals). ...or should I separate the two?
Thanks!
Here's a CF8 way of setting up the faculty CFC. Notice that I didn't use the 'instance' scope 'cause when it's time to upgrade to CF9, u can remove the getters/setters and add accessor=true
to the cfcomponent
and you're done. However, you may find adding an artificial 'instance' scope useful when you need to get the data out of the CFC as a struct for DAO to persist your object.
<cfcomponent>
<!--- does nothing in CF8 other then for documentation purposes --->
<cfproperty name="id">
<cfproperty name="department">
<!--- if you want to type your param and return type for functions in CF8, use CFML --->
<cfscript>
function init (id, department)
{
setId(id);
setDepartment(department);
return this;
}
function getId() {
return variables.id;
}
function setId(id) {
variables.id = arguments.id;
}
// do the same for dept
// make use of Snippet in CFEclipse / CF Builder to gen for you
</cfscript>
</cfcomponent>
can I also have methods in my component that deals with the whole (like a search function for all individuals). ...or should I separate the two?
Usually in the CF world (inspired by the Java world), we'd separate them into FooService
with no state, and cache your FooService
as singleton in Application
scope. Then implement the Create Read Update Delete (CRUD) methods that talk to the DB in FooDAO
(data access object) layer. Your FooService
would then call the CRUD methods in FooDAO
to read (and populate) a Foo
object for you.
精彩评论