BoxLang ๐ A New JVM Dynamic Language Learn More...
Copyright Since 2005 ColdBox Platform by Luis Majano
and Ortus Solutions, Corp
www.coldbox.org | www.ortussolutions.com
Welcome to the Flat ColdBox application template! ๐ This is the traditional, straightforward template for building HMVC (Hierarchical Model-View-Controller) web applications using Adobe ColdFusion, Lucee, or BoxLang.
The Flat template uses the traditional ColdBox structure where all application files reside in the web root. This is the most common and widely-used ColdBox template, perfect for:
๐ก Perfect for: Learning projects, rapid prototyping, internal tools, traditional hosting environments, and teams familiar with standard CFML application structures.
๐ Need enhanced security? Check out the Modern Template which separates application code from the web root.
Before getting started, ensure you have the following installed on your operating system:
CommandBox - CLI toolchain, package manager, and server runtime
CFML Engine - Choose your preferred engine:
Java (Optional) - For Maven-based Java dependencies
The Flat template follows the traditional ColdBox HMVC structure with all files in the web root:
โโโ ๐ Application.cfc # Application bootstrap & settings
โโโ ๐ index.cfm # Front controller
โโโ ๐จ favicon.ico # Site favicon
โโโ ๐ค robots.txt # SEO robots file
โ
โโโ ๐ config/ # Application configuration
โ โโโ ColdBox.cfc # Framework settings
โ โโโ Router.cfc # URL routing definitions
โ โโโ WireBox.cfc # Optional DI mappings
โ
โโโ ๐ handlers/ # Event handlers (controllers)
โ โโโ Main.cfc # Default handler
โ
โโโ ๐ models/ # Business logic layer
โ โโโ (your models here)
โ
โโโ ๐ views/ # View templates
โ โโโ main/ # Views for Main handler
โ
โโโ ๐ layouts/ # Layout templates
โ โโโ Main.cfm # Default layout
โ
โโโ ๐ includes/ # Public assets (CSS, JS, images)
โ โโโ css/
โ โโโ js/
โ โโโ images/
โ
โโโ ๐ modules_app/ # Application modules
โ โโโ (your modules here)
โ
โโโ ๐ tests/ # Test suites
โ โโโ specs/ # Test specifications
โ โ โโโ integration/ # Integration tests
โ โ โโโ unit/ # Unit tests
โ โโโ Application.cfc # Test bootstrap
โ โโโ runner.cfm # Test runner
โ
โโโ ๐ lib/ # Framework libraries
โ โโโ coldbox/ # ColdBox framework
โ โโโ testbox/ # TestBox testing framework
โ
โโโ ๐ docker/ # Docker configuration
โ โโโ Dockerfile
โ โโโ docker-compose.yml
โ
โโโ ๐ box.json # CommandBox package descriptor
โโโ ๐ server.json # Server configuration
โโโ ๐ .env # Environment variables
โโโ ๐ pom.xml # Maven Java dependencies
โโโ ๐ .cfformat.json # Code formatting rules
handlers/
- Event handlers (controllers) that respond to user requestsmodels/
- Service objects, beans, and business logicviews/
- HTML templates rendered by handlerslayouts/
- Page layouts that wrap viewsconfig/
- Application and framework configurationtests/
- BDD/TDD test suites using TestBoxmodules_app/
- Modular HMVC applications within your applib/
- Third-party frameworks installed by CommandBoxFirst, install all required dependencies including ColdBox and TestBox:
box install
This command reads box.json
and installs:
lib/coldbox/
lib/testbox/
Start the embedded CommandBox server:
box server start
The application will be available at: http://localhost:PORT (CommandBox will display the actual port)
Open your browser and navigate to the server URL. You should see the ColdBox welcome page!
coldbox create handler
name=YourHandler actions=index,save
coldbox create model name=UserService
coldbox create integration-test handler=YourHandler
The Flat template uses a simple bootstrap flow:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 1. User Request โ index.cfm (Front Controller) โ
โ 2. index.cfm calls Application.cfc โ
โ 3. Application.cfc bootstraps ColdBox framework โ
โ 4. ColdBox loads config/ColdBox.cfc โ
โ 5. ColdBox loads config/Router.cfc โ
โ 6. ColdBox executes handler action โ
โ 7. Handler renders view/layout or returns data โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Application.cfc
- Application bootstrap:
component {
this.name = "My ColdBox Application";
this.sessionManagement = true;
// ColdBox Bootstrap Settings
COLDBOX_APP_ROOT_PATH = getDirectoryFromPath(getCurrentTemplatePath());
COLDBOX_APP_MAPPING = "";
COLDBOX_CONFIG_FILE = "";
// Java integration for lib/ folder
this.javaSettings = {
loadPaths: [expandPath("./lib")]
};
}
config/ColdBox.cfc
- Framework configuration:
config/Router.cfc
- URL routing:
Format your code using CFFormat:
# Format all CFML code
box run-script format
# Check formatting without changes
box run-script format:check
# Watch for changes and auto-format
box run-script format:watch
Execute your test suites:
# Run all tests
box testbox run
# Run specific test bundle
box testbox run bundles=tests.specs.integration.MainSpec
# Run with coverage
box testbox run --verbose
Use ColdBox CLI to generate code:
# Create a handler with actions
coldbox create handler name=Users actions=index,create,save,delete
# Create a model with unit test
coldbox create model name=UserService methods=getAll,save,delete --open
# Create an integration test
coldbox create integration-test handler=Users
# Create a complete REST resource (handler + views + tests)
coldbox create resource name=Products --plural
# Start server
box server start
# Stop server
box server stop
# Restart server
box server restart
# Open server in browser
box server open
# View server logs
box server log
The Flat template includes a comprehensive testing setup using TestBox, a BDD/TDD testing framework.
tests/
โโโ Application.cfc # Test bootstrap
โโโ runner.cfm # Browser test runner
โโโ specs/
โโโ integration/ # Integration tests (test full request lifecycle)
โ โโโ MainSpec.cfc
โโโ unit/ # Unit tests (test individual components)
โโโ (your tests here)
# Run all tests
box testbox run
# Run specific test bundle
box testbox run bundles=tests.specs.integration.MainSpec
# Run tests and generate coverage report
box testbox run --verbose
# Run tests in browser
box server start
# Navigate to: http://localhost:PORT/tests/runner.cfm
Integration tests extend coldbox.system.testing.BaseTestCase
:
component extends="coldbox.system.testing.BaseTestCase" {
function beforeAll() {
super.beforeAll();
}
function run() {
describe("Main Handler", function() {
beforeEach(function(currentSpec) {
// CRITICAL: Call setup() to reset request context
setup();
});
it("can render the homepage", function() {
var event = this.get("main.index");
expect(event.getValue(name="welcomeMessage", private=true))
.toBe("Welcome to ColdBox!");
});
it("can return RESTful data", function() {
var event = this.post("main.data");
expect(event.getRenderedContent()).toBeJSON();
});
it("can handle relocations", function() {
var event = execute(event="main.doSomething");
expect(event.getValue("relocate_event", "")).toBe("main.index");
});
});
}
}
The BaseTestCase
provides helpful methods:
this.get(event)
- Execute GET requestthis.post(event, params)
- Execute POST requestthis.put(event, params)
- Execute PUT requestthis.delete(event)
- Execute DELETE requestexecute(event, private, prePostExempt)
- Execute any eventgetRequestContext()
- Get current request contextโ
Always call setup()
in beforeEach()
to reset the request context โ
Test one thing per test case โ
Use
descriptive names for your test suites and specs โ
Test both success and failure paths โ
Mock
external dependencies to isolate your tests
If your project relies on Java third-party libraries, you can use the
included Maven pom.xml
file.
pom.xml
:<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>
mvn install
This downloads all JARs to the lib/
folder, which is
automatically loaded by Application.cfc
via this.javaSettings.loadPaths
.
# Install/update dependencies
mvn install
# Remove all downloaded JARs
mvn clean
# Update all dependencies to latest versions
mvn versions:use-latest-versions
The Application.cfc
automatically loads all JARs from
the lib/
folder:
this.javaSettings = {
loadPaths: [expandPath("./lib")],
loadColdFusionClassPath: true,
reloadOnChange: false
};
The template includes Docker configuration for containerized deployments.
Build a Docker image using the CommandBox base image:
# Build the image
box run-script docker:build
# Run the container
box run-script docker:run
# Access container bash
box run-script docker:bash
The template includes a docker-compose.yml
file with
support for multiple databases:
# Start the stack (app + database)
box run-script docker:stack up
# Stop the stack
box run-script docker:stack down
# View logs
box run-script docker:stack logs
Supported Databases:
Edit docker/docker-compose.yml
to configure your
preferred database.
The included docker/Dockerfile
uses the official
CommandBox Docker image:
FROM ortussolutions/commandbox:latest
# Copy app files
COPY . /app
# Install dependencies
RUN box install
# Expose port
EXPOSE 8080
# Start server
CMD ["box", "server", "start"]
The template uses a .env
file for environment-specific configuration.
cp .env.example .env
.env
with your settings:# Application Settings
APPNAME=My Awesome App
ENVIRONMENT=development
# Database Settings
DB_HOST=localhost
DB_PORT=3306
DB_NAME=myapp
DB_USER=root
DB_PASSWORD=secret
# API Keys
API_KEY=your-api-key-here
getSystemSetting()
:// In config/ColdBox.cfc
variables.coldbox = {
appName: getSystemSetting("APPNAME", "Default App Name")
};
// In your handlers/models
var dbHost = getSystemSetting("DB_HOST", "localhost");
var apiKey = getSystemSetting("API_KEY");
The template automatically detects the environment:
Configure environment-specific settings in config/ColdBox.cfc
:
function development() {
variables.coldbox.handlersIndexAutoReload = true;
}
function production() {
variables.coldbox.handlersIndexAutoReload = false;
variables.coldbox.handlerCaching = true;
}
The Flat template leverages WireBox, ColdBox's dependency injection framework.
Use the @inject
annotation to inject dependencies:
// In a handler
component extends="coldbox.system.EventHandler" {
property name="userService" inject="UserService";
function index(event, rc, prc) {
prc.users = userService.getAll();
event.setView("users/index");
}
}
// models/UserService.cfc
component singleton {
property name="log" inject="logbox:logger: {this}";
function getAll() {
log.info("Fetching all users");
return queryExecute("SELECT * FROM users");
}
function save(required struct data) {
// Save user logic
}
}
WireBox provides a powerful injection DSL:
@inject="model"
- Inject by model name@inject="id:MyService"
- Inject by specific ID@inject="provider:UserService"
- Inject a provider (lazy loading)@inject="logbox:logger: {this}
- Inject a logger for this component@inject="cachebox:default"
- Inject the default cache@inject="wirebox"
- Inject the WireBox injector itselfConfigure WireBox in config/WireBox.cfc
(optional):
component extends="coldbox.system.ioc.config.Binder" {
function configure() {
// Map custom objects
map("SecurityService").to("models.security.SecurityService");
// Map interfaces to implementations
map("IUserService").to("models.UserService");
}
}
Handlers (controllers) respond to user requests and coordinate application flow.
component extends="coldbox.system.EventHandler" {
/**
* Default action
*/
function index(event, rc, prc) {
prc.welcomeMessage = "Hello World!";
event.setView("main/index");
}
/**
* RESTful JSON response
*/
function data(event, rc, prc) {
return [
{id: 1, name: "Alice"},
{id: 2, name: "Bob"}
];
}
/**
* Relocation example
*/
function save(event, rc, prc) {
// Save logic here
relocate("main.index");
}
}
Every handler action receives three arguments:
event
- Request context with methods to get/set values, render
views, etc.rc
- Request collection (URL and FORM scopes combined)prc
- Private request collection (not accessible from URL)// Get request values
var id = event.getValue("id", 0);
var name = event.getPrivateValue("name");
// Set values
event.setValue("result", data);
event.setPrivateValue("user", userObj);
// Rendering
event.setView("users/edit");
event.setLayout("admin");
return event.renderData(data=result, type="json");
// Relocations
event.overrideEvent("users.list");
relocate("users.index");
Handlers support implicit lifecycle events:
function onAppInit(event, rc, prc) {
// Called once when application starts
}
function onRequestStart(event, rc, prc) {
// Called before each request
}
function onRequestEnd(event, rc, prc) {
// Called after each request
}
function onException(event, rc, prc) {
// Called when an exception occurs
var exception = prc.exception;
log.error("Error occurred", exception);
}
The template uses config/Router.cfc
to define URL routes.
component {
function configure() {
// Simple route
route("/about").to("main.about");
// Route with parameters
route("/users/:id").to("users.show");
// Route with closure
route("/api/health", function(event, rc, prc) {
return {status: "OK", timestamp: now()};
});
// Conventions-based routing (catch-all)
route(":handler/:action?").end();
}
}
resources("photos"); // Creates 7 RESTful routes
// Equivalent to:
// GET /photos -> photos.index
// GET /photos/new -> photos.new
// POST /photos -> photos.create
// GET /photos/:id -> photos.show
// GET /photos/:id/edit -> photos.edit
// PUT /photos/:id -> photos.update
// DELETE /photos/:id -> photos.delete
group({prefix: "/api/v1"}, function() {
route("/users").to("api.users.index");
route("/products").to("api.products.index");
});
The template includes VSCode configuration for enhanced development experience.
.vscode/settings.json
- IntelliSense for ColdBox and TestBox.vscode/tasks.json
- Quick tasks for common operationsRun CommandBox Task - Execute CommandBox tasks quickly Run TestBox Bundle - Run tests from current file
Usage:
Cmd+Shift+P
or Ctrl+Shift+P
)Tasks: Run Build Task
โงโB
(Mac) /
Shift+Ctrl+B
(Windows)Install these VSCode extensions for the best development experience:
ColdBox is a professional, conventions-based HMVC framework packed with features:
CFCasts - Premium video training platform https://www.cfcasts.com
Get access to hundreds of ColdBox tutorials, from beginner to advanced topics.
coldbox
ColdBox is a professional open-source project completely funded by the community and Ortus Solutions, Corp.
Support ColdBox development and get awesome benefits:
Visit our Patreon page: https://patreon.com/ortussolutions
Apache License, Version 2.0.
See LICENSE for details.
"I am the way, and the truth, and the life; no one comes to the Father, but by me (JESUS)" โ John 14:6
All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
renderView()
to new standard of view()
allowPublicKeyRetrieval=true
to the db
connection string.cfconfig.json
and .env.example
modules_app
convention.build
foldertests
to new standards
$
box install cbtemplate-flat