# ContactService.cfc

Here is our service layer and we have added some logging just for fun :). Notice that this object is a singleton and has some dependency injection.

```
coldbox create model name=ContactService persistence=singleton --open
```

Then spice it up

```javascript
component accessors="true" singleton{

    // Dependency Injection
    property name="dao" inject="ContactDAO";
    property name="log" inject="logbox:logger:{this}";
    property name="populator" inject="wirebox:populator";
    property name="wirebox" inject="wirebox";

    function init(){
        return this;
    }

    /**
    * Get all contacts as an array of objects or query
    */
    function list(boolean asQuery=false){
        var q = dao.getAllUsers();
        log.info("Retrieved all contacts", q.recordcount);

        if( asQuery ){ return q; }

        // convert to objects
        var contacts = [];
        for(var x=1; x lte q.recordcount; x++){
            arrayAppend( contacts, populator.populateFromQuery( wirebox.getInstance("Contact"), q, x ) );
        }

        return contacts;
    }

    /**
    * Get a persisted contact by ID or new one if 0 or no records
    */
    function get(required contactID=0){
        var q = dao.getContact(arguments.contactID);
        // if 0 or no records
        if( contactID eq 0 OR q.recordcount eq 0 ){
            // return a new object
            return wirebox.getInstance("Contact");
        }
        // Else return the object
        return populator.populateFromQuery( wirebox.getInstance("Contact"), q, 1 );
    }

    ... ALL OTHER METHODS HERE  ....

}
```

Now, some observations of the code:

* We use the populator object that is included in WireBox to make our lives easier so we can populate objects from queries and deal with objects.
* We also inject a reference to the object factory WireBox so it can create `Contact` objects for us. Why? Well what if those objects had dependencies as well.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://coldbox.ortusbooks.com/the-basics/models/coding-solo-style/contactservice.cfc.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
