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:
- π Quick Prototyping - Get started fast without complex directory structures
- π Learning ColdBox - Straightforward layout makes it easy to understand the framework
- π§ Simple Deployments - Traditional hosting setup with minimal configuration
- π Universal Compatibility - Works with Adobe CF, Lucee, and BoxLang
π‘ 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
- π₯ Installation: https://commandbox.ortusbooks.com/setup/installation
- π Minimum Version: 6.0+
- π― Used for: dependency management, server starting, testing, and task automation
-
CFML Engine - Choose your preferred engine:
- Adobe ColdFusion 2018+ - https://www.adobe.com/products/coldfusion-family.html
- Lucee 5.x+ - https://www.lucee.org
- BoxLang 1.0+ - https://boxlang.io
-
Java (Optional) - For Maven-based Java dependencies
- Required only if using Java libraries via Maven
- Compatible with Java 11+ (Java 21 recommended)
- Directory Structure
- Quick Start
- Application Bootstrap
- Development Workflows
- Testing
- Java Dependencies
- Docker Support
- Environment Configuration
- Dependency Injection
- Handler Patterns
- Routing
- VSCode Helpers
- ColdBox Features
- Learning Resources
- Sponsors
- Important Links
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 CommandBox
First, install all required dependencies including ColdBox and TestBox:
box install
This command reads box.json
and installs:
- ColdBox framework to
lib/coldbox/
- TestBox testing framework to
lib/testbox/
- Development tools (cfformat, coldbox-cli, testbox-cli)
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!
- Create handlers:
coldbox create handler name=YourHandler actions=index,save
- Create models:
coldbox create model name=UserService
- Create tests:
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:
- Application name and settings
- Event handlers and implicit events
- Module locations
- Caching strategies
- Logging configuration
config/Router.cfc
- URL routing:
- RESTful API routes
- Resource routes
- Conventions-based 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.
- Find your dependency at https://central.sonatype.com/
- Copy the Maven coordinates (groupId, artifactId, version)
- Add to
pom.xml
:
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>
- Download the JARs:
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:
- MySQL
- PostgreSQL
- Microsoft SQL Server
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.
- Copy the example file:
cp .env.example .env
- Edit
.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
- Access in your code using
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:
- Development - Local development machine
- Staging - Pre-production environment
- Production - Live 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 itself
Configure 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 operations
Run CommandBox Task - Execute CommandBox tasks quickly Run TestBox Bundle - Run tests from current file
Usage:
- Open Command Palette (
Cmd+Shift+P
orCtrl+Shift+P
) - Select
Tasks: Run Build Task
- Or use shortcut:
β§βB
(Mac) /Shift+Ctrl+B
(Windows)
Install these VSCode extensions for the best development experience:
- CFML by KamasamaK - Language support and IntelliSense
- CFLint - CFML linting
- vscode-coldbox - ColdBox snippets and commands
ColdBox is a professional, conventions-based HMVC framework packed with features:
- Conventions instead of configuration
- Modern URL routing
- RESTFul APIs
- Hierarchical MVC with modules
- Event-driven programming
- Async and parallel programming
- Integration & unit testing
- Dependency injection with WireBox
- Caching with CacheBox
- Logging with LogBox
- Extensive ecosystem
- ColdBox Docs - https://coldbox.ortusbooks.com
- WireBox Docs - https://wirebox.ortusbooks.com
- CacheBox Docs - https://cachebox.ortusbooks.com
- LogBox Docs - https://logbox.ortusbooks.com
- TestBox Docs - https://testbox.ortusbooks.com
CFCasts - Premium video training platform https://www.cfcasts.com
Get access to hundreds of ColdBox tutorials, from beginner to advanced topics.
- ColdBox Forum - https://community.ortussolutions.com
- Ortus Slack - https://boxteam.ortussolutions.com
- Stack Overflow - Tag your questions with
coldbox
ColdBox is a professional open-source project completely funded by the community and Ortus Solutions, Corp.
Support ColdBox development and get awesome benefits:
- π₯ CFCasts Account - Access to premium video training
- π¦ ForgeBox Pro - Advanced package management features
- π« Event Discounts - Discounts on Into the Box conference
- π Recognition - Your logo on our website and documentation
Visit our Patreon page: https://patreon.com/ortussolutions
- Website - https://www.coldbox.org
- Documentation - https://coldbox.ortusbooks.com
- GitHub - https://github.com/ColdBox/coldbox-platform
- ForgeBox - https://forgebox.io/view/coldbox
- Ortus Solutions - https://www.ortussolutions.com
- Ortus Community - https://community.ortussolutions.com
- CFCasts Training - https://www.cfcasts.com
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