Adding Our Update Process using Quick and Mementifier
Background
The update process is more complicated for any number of reasons
We want to avoid duplication
Data from the UI is not always complete and fields needs to calculated
There might be business logic which needs to be done elsewhere on a save
There are many ways to solve these problems including DYI, triggers in the database itself. Another is with something called ORM. ORM is not for every situation and CF has a built in one called Hibernate which will elicit everything cheers, boos and "meh" depending on to whom you're speaking.
The whole point of an ORM system is to hide away a great deal of the boilerplate code and to encapsulate other logic which might need to exist so your devs don't forget about it when they are creating new functionality
Quick is a very lightweight ORM system which is built on QB. A Quick entity is a cfc which typically has a property for each field in the database. It also has ways of keeping track of primary keys, tasks to do on an insert, an update and so on. It can be as simple or complex as you choose.
Creating an Entity
In CommandBox from the root of the website type
install quick- This the ORM engine itselfIn CommandBox from the root of the website type
install mementifier- This is a module which makes it easier to render CF components into customizable structsIn CommandBox type
install commandbox-quickgen- This is a tool that can generate quick entities from existing database tables.First we need to give CommandBox a datasource: type
quickgen configurea. type 'y' to start the wizard b. Datasource Name : justEnough c. Use the arrow keys and space bar to choose MySQL d. Database Name?: DBNAME e. Username: USERNAME f. Password: PASSWORD g. Host: justenough.cyqisqc1fx3i.us-west-2.rds.amazonaws.com h. Port: 3306 i. Do you want to make MYSQL the default grammar for QB?: n j. Do you want to write this datasource to the .env file to use with cfmigrations?: n\Then we need to generate the entity:
quickgen generate datasource=justEnough dbname=DBNAME tableName=usersTo format it type
cfformat run models/entities/users.cfc --overwrite
This will create the users entity in /models/entities.
Creating The Update Handler
function update( event, rc, prc ){
var valid = validateOrFail(
target = rc,
constraints = {
"userId" : { "required" : true, "type" : "numeric", "min" : 1 },
"email" : { "required" : true, "type" : "email", "size" : "1..256" },
"password" : { "required" : true, "type" : "string", "size" : "1..256" }
}
);
var updated = userService.updateUser( valid.userId, valid.email, valid.password );
prc.response.setData( updated ).addMessage( "user updated" );
}Creating the updateUser() Method
function updateUser( required numeric userId, required string email, required string password){
return userEntity
.find(userId)
.populate({
email:arguments.email,
password:arguments.password
})
.save()
.getMemento();
}Last updated