BoxLang ๐Ÿš€ A New JVM Dynamic Language Learn More...

Flat ColdBox App Template

v8.0.0s+33 MVC


ColdBox Snapshots Total Downloads Latest Stable Version Apache2 License

Copyright Since 2005 ColdBox Platform by Luis Majano and Ortus Solutions, Corp
www.coldbox.org | www.ortussolutions.com


๐Ÿ“ฆ ColdBox Flat Application Template

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.

๐ŸŒŸ What is the "Flat" Template?

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.

โš™๏ธ Requirements

Before getting started, ensure you have the following installed on your operating system:

  1. CommandBox - CLI toolchain, package manager, and server runtime

  2. CFML Engine - Choose your preferred engine:

  3. Java (Optional) - For Maven-based Java dependencies

    • Required only if using Java libraries via Maven
    • Compatible with Java 11+ (Java 21 recommended)

๐Ÿ“‹ Table of Contents

๐Ÿ“ Directory Structure

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

Key Directories

  • handlers/ - Event handlers (controllers) that respond to user requests
  • models/ - Service objects, beans, and business logic
  • views/ - HTML templates rendered by handlers
  • layouts/ - Page layouts that wrap views
  • config/ - Application and framework configuration
  • tests/ - BDD/TDD test suites using TestBox
  • modules_app/ - Modular HMVC applications within your app
  • lib/ - Third-party frameworks installed by CommandBox

๐Ÿš€ Quick Start

1. Install Dependencies

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)

2. Start the Server

Start the embedded CommandBox server:

box server start

The application will be available at: http://localhost:PORT (CommandBox will display the actual port)

3. View Your Application

Open your browser and navigate to the server URL. You should see the ColdBox welcome page!

4. Start Coding

  • 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

๐Ÿ”ง Application Bootstrap

How It Works

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              โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Key Configuration Files

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

๐Ÿ› ๏ธ Development Workflows

Code Formatting

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

Running Tests

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

Creating Scaffolding

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

Server Management

# 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

๐Ÿงช Testing

The Flat template includes a comprehensive testing setup using TestBox, a BDD/TDD testing framework.

Test Structure

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)

Running Tests

# 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

Writing Integration Tests

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");
            });
        });
    }
}

Testing Helpers

The BaseTestCase provides helpful methods:

  • this.get(event) - Execute GET request
  • this.post(event, params) - Execute POST request
  • this.put(event, params) - Execute PUT request
  • this.delete(event) - Execute DELETE request
  • execute(event, private, prePostExempt) - Execute any event
  • getRequestContext() - Get current request context

Best Practices

โœ… 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

โ˜• Java Dependencies

If your project relies on Java third-party libraries, you can use the included Maven pom.xml file.

Adding Java Dependencies

  1. Find your dependency at https://central.sonatype.com/
  2. Copy the Maven coordinates (groupId, artifactId, version)
  3. Add to pom.xml :
<dependencies>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.10.1</version>
    </dependency>
</dependencies>
  1. Download the JARs:
mvn install

This downloads all JARs to the lib/ folder, which is automatically loaded by Application.cfc via this.javaSettings.loadPaths.

Managing Java Dependencies

# Install/update dependencies
mvn install

# Remove all downloaded JARs
mvn clean

# Update all dependencies to latest versions
mvn versions:use-latest-versions

Automatic Class Loading

The Application.cfc automatically loads all JARs from the lib/ folder:

this.javaSettings = {
    loadPaths: [expandPath("./lib")],
    loadColdFusionClassPath: true,
    reloadOnChange: false
};

๐Ÿณ Docker Support

The template includes Docker configuration for containerized deployments.

Building Docker Images

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

Docker Compose Stack

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.

Dockerfile

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"]

๐ŸŒ Environment Configuration

The template uses a .env file for environment-specific configuration.

Setup

  1. Copy the example file:
cp .env.example .env
  1. 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
  1. 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");

Environment Detection

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;
}

๐Ÿ’‰ Dependency Injection

The Flat template leverages WireBox, ColdBox's dependency injection framework.

Basic Injection

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");
    }
}

Model Example

// 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
    }
}

Injection DSL

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

Configuration

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");
    }
}

๐ŸŽฏ Handler Patterns

Handlers (controllers) respond to user requests and coordinate application flow.

Basic Handler

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");
    }
}

Handler Arguments

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)

Common Event Methods

// 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");

Lifecycle Methods

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);
}

๐Ÿ›ฃ๏ธ Routing

The template uses config/Router.cfc to define URL routes.

Basic 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();
    }
}

RESTful Resources

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

Route Groups

group({prefix: "/api/v1"}, function() {
    route("/users").to("api.users.index");
    route("/products").to("api.products.index");
});

๐Ÿ”ง VSCode Helpers

The template includes VSCode configuration for enhanced development experience.

Included Files

  • .vscode/settings.json - IntelliSense for ColdBox and TestBox
  • .vscode/tasks.json - Quick tasks for common operations

Custom Tasks

Run CommandBox Task - Execute CommandBox tasks quickly Run TestBox Bundle - Run tests from current file

Usage:

  1. Open Command Palette (Cmd+Shift+P or Ctrl+Shift+P)
  2. Select Tasks: Run Build Task
  3. 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 Features

ColdBox is a professional, conventions-based HMVC framework packed with features:

๐Ÿ“š Learning Resources

Official Documentation

Video Learning

CFCasts - Premium video training platform https://www.cfcasts.com

Get access to hundreds of ColdBox tutorials, from beginner to advanced topics.

Community

๐Ÿ’ฐ Sponsors

ColdBox is a professional open-source project completely funded by the community and Ortus Solutions, Corp.

Become a Sponsor

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

๐Ÿ“„ License

Apache License, Version 2.0.

See LICENSE for details.

๐Ÿ™ THE DAILY BREAD

"I am the way, and the truth, and the life; no one comes to the Father, but by me (JESUS)" โ€” John 14:6

Changelog

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.


Unreleased

8.0.0s - 2025-10-10

7.4.0 - 2025-06-07

Added

  • More maven pom.xml files for better IDE support

Fixed

  • Gitignore updates so it doesn't ignore 'config/modules'

7.3.0 - 2023-05-19

Fixed

  • Changed renderView() to new standard of view()
  • Added allowPublicKeyRetrieval=true to the db connection string
  • Added missing bundle name and version in .cfconfig.json and .env.example

7.2.0 - 2023-05-16

Fixed

  • Added correct dependency versions

[6.20.0] => 2023-MAR-20

Added

  • Added routing conventions to make it easier for the cli to add routes.

[6.19.0] => 2023-MAR-20

Added

  • Forgot the modules_app convention.

[6.18.0] => 2023-MAR-18

Fixed

  • GH actions

[6.17.0] => 2023-MAR-18

Added

  • Changelog Tracking
  • Github actions for auto building
  • Latest ColdBox standards
  • UI Updates
  • Latest Alpine + Bootstrap Combo
  • vscode introspection and helpers
  • Docker build and compose consolidation to the build folder
  • Cleanup of tests to new standards
  •   Ortus Solutions
  • Published
  • 8.0.0s+33 is the latest of 3 release(s)
    Published
  • Published on {{ getFullDate("2025-10-10T14:36:59Z") }}

$ box install cbtemplate-flat

No collaborators yet.
  • {{ getFullDate("2025-10-09T15:23:07Z") }}
  • {{ getFullDate("2025-10-10T14:36:59Z") }}
  • 34
  • 3