Homestar9

Untitled

Apr 24th, 2026 (edited)
21
0
Never
5
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 33.72 KB | None | 0 0
  1. <!-- COLDBOX-CLI:START -->
  2. <!-- ⚡ This section is managed by ColdBox CLI and will be refreshed on `coldbox ai refresh`. -->
  3. <!-- ⚠️ Do NOT edit content between COLDBOX-CLI:START and COLDBOX-CLI:END markers — changes will be overwritten. -->
  4.  
  5. # my-api - AI Agent Instructions
  6.  
  7. This is a ColdBox HMVC application using the **flat template structure** where all application code lives in the webroot. Compatible with Adobe ColdFusion 2018+, Lucee 5.x+, and BoxLang 1.0+.
  8.  
  9. ## Project Overview
  10.  
  11. **Language Mode:** CFML
  12. **ColdBox Version:** ^8.0.5+33
  13. **Template Type:** Flat (traditional webroot structure)
  14.  
  15. ## Application Structure
  16.  
  17. ```
  18. / - Application root (webroot)
  19. ├── Application.cfc - Bootstrap that directly loads ColdBox
  20. ├── index.cfm - Front controller
  21. ├── config/ - Framework and app configuration
  22. ├── handlers/ - Event handlers (controllers)
  23. ├── models/ - Service objects, business logic
  24. ├── views/ - HTML templates
  25. ├── layouts/ - Page layouts wrapping views
  26. ├── includes/ - Public assets (CSS, JS, images)
  27. ├── modules_app/ - Application modules (HMVC)
  28. ├── tests/ - Test suites
  29. └── lib/ - Framework dependencies
  30. ```
  31.  
  32. **Key Characteristics:**
  33. - Everything in webroot (simpler for traditional hosting)
  34. - No `/app` vs `/public` separation
  35. - All code is web-accessible by default
  36. - `COLDBOX_APP_MAPPING = ""` (empty, app at root)
  37.  
  38. ## Framework Knowledge
  39.  
  40. **Important:** The following sections contain essential framework documentation that is always available in your context. These guidelines cover core concepts, conventions, and best practices for ColdBox development.
  41.  
  42. ---
  43.  
  44. # ColdBox Framework Core Guidelines
  45. ## Overview
  46. ColdBox is a conventions-based HMVC (Hierarchical Model-View-Controller) framework for CFML and BoxLang applications. It provides a complete ecosystem for building modern, scalable web applications and REST APIs.
  47. ## Application Structure
  48. ---
  49. title: ColdBox Flat Project Structure
  50. description: Canonical flat ColdBox directory layout for legacy or simplified apps, defining where handlers, models, views, layouts, interceptors, modules, and tests should live.
  51. ---
  52. ```
  53. /config - Application configuration
  54. /handlers - Event handlers (controllers)
  55. /models - Business logic and services
  56. /views - View templates
  57. /layouts - Layout wrappers
  58. /interceptors - Event interceptors (AOP)
  59. /modules - ColdBox modules (sub-applications)
  60. /tests - TestBox test suites
  61. ```
  62. ## Event Handlers (Controllers)
  63. ### Handler Conventions
  64. - Extend `coldbox.system.EventHandler`
  65. - Located in `/handlers/` directory
  66. - Use plural nouns: `Users.cfc`, `Orders.cfc`, `Products.cfc`
  67. - Actions are public functions receiving `event`, `rc`, `prc`
  68. ### Basic Handler
  69. ```boxlang
  70. class Users extends coldbox.system.EventHandler {
  71. property name="userService" inject;
  72. property name="log" inject="logbox:logger:{this}";
  73. function index( event, rc, prc ) {
  74. prc.users = userService.getAll()
  75. event.setView( "users/index" )
  76. }
  77. function show( event, rc, prc ) {
  78. prc.user = userService.getById( rc.id ?: 0 )
  79. event.setView( "users/show" )
  80. }
  81. function create( event, rc, prc ) {
  82. var user = userService.create( rc )
  83. flash.put( "notice", "User created successfully" )
  84. relocate( "users.show", { id: user.id } )
  85. }
  86. }
  87. ```
  88. ### RESTful Handler
  89. ```boxlang
  90. class API extends coldbox.system.EventHandler {
  91. property name="userService" inject;
  92. function index( event, rc, prc ) {
  93. prc.data = userService.getAll()
  94. event.renderData(
  95. data = prc.data,
  96. formats = "json,xml"
  97. )
  98. }
  99. function show( event, rc, prc ) {
  100. prc.data = userService.getById( rc.id ?: 0 )
  101. event.renderData( data = prc.data )
  102. }
  103. function create( event, rc, prc ) {
  104. prc.data = userService.create( rc )
  105. event.renderData(
  106. data = prc.data,
  107. statusCode = 201
  108. )
  109. }
  110. function update( event, rc, prc ) {
  111. prc.data = userService.update( rc.id, rc )
  112. event.renderData( data = prc.data )
  113. }
  114. function delete( event, rc, prc ) {
  115. userService.delete( rc.id )
  116. event.renderData(
  117. data = { message: "Deleted successfully" },
  118. statusCode = 204
  119. )
  120. }
  121. }
  122. ```
  123. ## Request Context (Event Object)
  124. The `event` object is your gateway to request data and framework features.
  125. ### Getting/Setting Values
  126. ```boxlang
  127. // Get from RC (request collection - URL/FORM merged)
  128. var userId = event.getValue( "userId", 0 )
  129. var email = event.getTrimValue( "email", "" )
  130. // Set in PRC (private request collection - safe, internal)
  131. event.setValue( "userName", user.name )
  132. event.setPrivateValue( "internalData", sensitiveData )
  133. // Param a value (set default if not exists)
  134. event.paramValue( "page", 1 )
  135. event.paramValue( "perPage", 25 )
  136. // Get entire collections
  137. var rc = event.getCollection()
  138. var prc = event.getPrivateCollection()
  139. ```
  140. ### Request Metadata
  141. ```boxlang
  142. // Current execution info
  143. var handler = event.getCurrentHandler() // "users"
  144. var action = event.getCurrentAction() // "index"
  145. var eventName = event.getCurrentEvent() // "users.index"
  146. var module = event.getCurrentModule() // "admin" (if in module)
  147. // View/Layout info
  148. var view = event.getCurrentView()
  149. var layout = event.getCurrentLayout()
  150. // Routing info
  151. var route = event.getCurrentRoute()
  152. var routeName = event.getCurrentRouteName()
  153. ```
  154. ### Rendering
  155. ```boxlang
  156. // Set view to render
  157. event.setView( "users/index" )
  158. event.setView( view="users/show", layout="custom" )
  159. // Set layout only
  160. event.setLayout( "admin" )
  161. // Render data (JSON/XML/PDF/etc)
  162. event.renderData(
  163. data = users,
  164. type = "json",
  165. statusCode = 200
  166. )
  167. // Prevent rendering
  168. event.noRender()
  169. // Render nothing (204 response)
  170. event.noExecution()
  171. ```
  172. ### Navigation
  173. ```boxlang
  174. // Relocate to another event
  175. relocate( "users.index" )
  176. relocate( event="users.show", queryString="id=5" )
  177. // Build links
  178. var url = event.buildLink( "users.show" )
  179. var url = event.buildLink( to="users.edit", queryString="id=#user.id#" )
  180. var url = event.buildLink( to="api.users.show", ssl=true )
  181. ```
  182. ### HTTP Operations
  183. ```boxlang
  184. // Get HTTP method
  185. var method = event.getHTTPMethod() // GET, POST, PUT, DELETE
  186. // Check HTTP method
  187. if ( event.isGET() ) { }
  188. if ( event.isPOST() ) { }
  189. if ( event.isPUT() ) { }
  190. if ( event.isDELETE() ) { }
  191. // Request type
  192. if ( event.isAjax() ) { }
  193. if ( event.isSSL() ) { }
  194. // Set HTTP headers
  195. event.setHTTPHeader( name="X-Custom-Header", value="value" )
  196. event.setHTTPHeader( statusCode=404, statusText="Not Found" )
  197. ```
  198. ## Dependency Injection (WireBox)
  199. ### Property Injection
  200. ```boxlang
  201. class Users extends coldbox.system.EventHandler {
  202. // Auto-inject by name convention
  203. property name="userService" inject;
  204. // Inject from specific path
  205. property name="utils" inject="models.Utils";
  206. // Inject by ID
  207. property name="mailService" inject="id:MailService";
  208. // Inject using DSL
  209. property name="cache" inject="cachebox:default";
  210. property name="log" inject="logbox:logger:{this}";
  211. property name="settings" inject="coldbox:setting:mySettings";
  212. property name="wirebox" inject="wirebox";
  213. }
  214. ```
  215. ### getInstance() Method
  216. ```boxlang
  217. // Get instances programmatically
  218. var userService = getInstance( "UserService" )
  219. var cache = getInstance( "cachebox:default" )
  220. var settings = getInstance( "coldbox:setting:appName" )
  221. ```
  222. ## Routing
  223. ### Route Configuration
  224. Located in `config/Router.cfc`:
  225. ```boxlang
  226. function configure() {
  227. // Enable full rewrites
  228. setFullRewrites( true )
  229. // Basic route
  230. route( "/" ).to( "main.index" )
  231. route( "/about" ).to( "main.about" )
  232. // Route with placeholders
  233. route( "/blog/:year/:month/:day/:slug" ).to( "blog.show" )
  234. // Optional placeholders
  235. route( "/search/:term?/:page?" ).to( "search.results" )
  236. // Constrained placeholders
  237. route( "/user/:id-numeric" ).to( "users.show" )
  238. route( "/blog/:year-regex:(\\d{4})" ).to( "blog.archive" )
  239. // Named routes
  240. route( "/contact" )
  241. .as( "contactPage" )
  242. .to( "main.contact" )
  243. // RESTful resources
  244. resources( "users" )
  245. // Creates: index, create, show, update, delete routes
  246. // API routes
  247. group( { pattern="/api/v1", handler="api" }, () => {
  248. route( "/users" ).to( "users.index" )
  249. route( "/users/:id" ).to( "users.show" )
  250. } )
  251. // Route to view directly
  252. route( "/terms" ).toView( "legal/terms" )
  253. // Route to response function
  254. route( "/health" ).toResponse( ( event, rc, prc ) => {
  255. return { status: "ok", timestamp: now() }
  256. } )
  257. // Redirect routes
  258. route( "/old-page" ).toRedirect( "/new-page", 301 )
  259. }
  260. ```
  261. ### Module Routing
  262. ```boxlang
  263. // In module's config/Router.cfc
  264. function configure() {
  265. route( "/" ).to( "home.index" )
  266. route( "/products" ).to( "products.list" )
  267. }
  268. // Access: /mymodule/products
  269. // Or with custom entrypoint: /shop/products
  270. ```
  271. ## Interceptors (AOP)
  272. Interceptors provide aspect-oriented programming for cross-cutting concerns.
  273. ### Built-in Interception Points
  274. ```boxlang
  275. // Application lifecycle
  276. afterConfigurationLoad
  277. afterAspectsLoad
  278. afterCacheStartup
  279. onException
  280. onRequestCapture
  281. preProcess
  282. preEvent
  283. postEvent
  284. postProcess
  285. preLayout
  286. postLayout
  287. preRender
  288. postRender
  289. // Module lifecycle
  290. preModuleLoad
  291. postModuleLoad
  292. preModuleUnload
  293. postModuleUnload
  294. ```
  295. ### Creating Interceptors
  296. ```boxlang
  297. class SecurityInterceptor extends coldbox.system.Interceptor {
  298. property name="securityService" inject;
  299. function preProcess( event, interceptData ) {
  300. if ( !securityService.isLoggedIn() && !event.valueExists( "public" ) ) {
  301. flash.put( "error", "Please log in" )
  302. relocate( "auth.login" )
  303. }
  304. }
  305. function onException( event, interceptData ) {
  306. // interceptData contains: exception, type, timestamp
  307. log.error(
  308. "Exception occurred: #interceptData.exception.message#",
  309. interceptData.exception
  310. )
  311. }
  312. }
  313. ```
  314. ### Registering Interceptors
  315. In `config/ColdBox.cfc`:
  316. ```boxlang
  317. interceptors = [
  318. { class="interceptors.SecurityInterceptor" },
  319. {
  320. class="interceptors.RequestLogger",
  321. properties={ logPath="/logs/requests" }
  322. }
  323. ]
  324. ```
  325. ### Announcing Custom Events
  326. ```boxlang
  327. // In handlers or models
  328. announceInterception( "onUserLogin", { user: user } )
  329. announceInterception( "onOrderComplete", { order: order, total: total } )
  330. // In interceptors - listen for custom events
  331. function onUserLogin( event, interceptData ) {
  332. var user = interceptData.user
  333. log.info( "User logged in: #user.email#" )
  334. }
  335. ```
  336. ## Modules
  337. Modules are self-contained sub-applications that can be plugged into any ColdBox application.
  338. ### Module Structure
  339. ```
  340. /modules/shop/
  341. ModuleConfig.cfc
  342. /handlers
  343. /models
  344. /views
  345. /layouts
  346. /interceptors
  347. config/Router.cfc
  348. ```
  349. ### Module Configuration
  350. ```boxlang
  351. component {
  352. this.title = "Shop Module"
  353. this.author = "Your Name"
  354. this.version = "1.0.0"
  355. this.entryPoint = "/shop"
  356. function configure() {
  357. settings = {
  358. currency: "USD",
  359. taxRate: 0.08
  360. }
  361. interceptors = [
  362. { class="interceptors.ShopSecurity" }
  363. ]
  364. }
  365. }
  366. ```
  367. ## Configuration (config/ColdBox.cfc)
  368. ```boxlang
  369. component {
  370. function configure() {
  371. coldbox = {
  372. appName = "My Application",
  373. reinitPassword = "",
  374. handlersIndexAutoReload = true, // Dev only
  375. handlerCaching = false, // Dev only
  376. viewCaching = false, // Dev only
  377. eventCaching = false, // Dev only
  378. defaultEvent = "main.index",
  379. requestStartHandler = "main.onRequestStart",
  380. requestEndHandler = "main.onRequestEnd",
  381. applicationStartHandler = "main.onAppInit",
  382. onInvalidEvent = "main.notFound",
  383. customErrorTemplate = "/views/main/error.cfm"
  384. }
  385. settings = {
  386. mySettings = "value",
  387. apiKey = getSystemSetting( "API_KEY", "" )
  388. }
  389. interceptors = [
  390. { class="interceptors.Security" }
  391. ]
  392. moduleSettings = {
  393. cbdebugger = {
  394. enabled = true
  395. }
  396. }
  397. }
  398. }
  399. ```
  400. ## Flash Scope
  401. Persist data across redirects:
  402. ```boxlang
  403. // Put data in flash
  404. flash.put( "notice", "User created successfully" )
  405. flash.put( "user", user )
  406. // Get from flash
  407. var notice = flash.get( "notice", "" )
  408. var user = flash.get( "user" )
  409. // Keep flash for next request
  410. flash.keep( "userData" )
  411. // Discard flash
  412. flash.discard( "tempData" )
  413. ```
  414. ## Best Practices
  415. - **Use RESTful naming** - Handlers are plural nouns, actions are standard REST verbs
  416. - **Leverage dependency injection** - Use `property inject` instead of manual creation
  417. - **Use PRC for internal data** - Keep RC for user input only
  418. - **Create service layers** - Keep handlers thin, move logic to services
  419. - **Use interceptors for cross-cutting concerns** - Security, logging, caching
  420. - **Build in modules** - Organize large applications into modules
  421. - **Use named routes** - Makes refactoring easier with `buildLink( name="routeName" )`
  422. - **Cache aggressively** - Use CacheBox for expensive operations
  423. - **Log appropriately** - Use LogBox with proper severity levels
  424. - **Test everything** - Use TestBox for unit and integration tests
  425. ## Documentation
  426. For complete ColdBox documentation, modules, and advanced features, consult the ColdBox MCP server or visit:
  427. https://coldbox.ortusbooks.com
  428.  
  429. ---
  430.  
  431. # CFML Core Guidelines
  432. ## Overview
  433. CFML (ColdFusion Markup Language) is a dynamic, rapid application development language for the JVM. It supports both tag-based and script-based syntax, making it flexible for different coding styles.
  434. ## Syntax Styles
  435. CFML supports two syntax styles that can be mixed in the same file:
  436. ### Script Syntax (Recommended)
  437. ```cfml
  438. component {
  439. property name="userService" inject;
  440. function getAll() {
  441. return userService.findAll();
  442. }
  443. function create( required struct data ) {
  444. return userService.create( data );
  445. }
  446. }
  447. ```
  448. ### Tag Syntax
  449. ```cfml
  450. <cfcomponent>
  451. <cffunction name="getAll" access="public" returntype="array">
  452. <cfreturn userService.findAll()>
  453. </cffunction>
  454. </cfcomponent>
  455. ```
  456. **Best Practice:** Use script syntax (CFScript) for better readability and consistency with modern languages.
  457. ## Component Structure
  458. ### Basic Component
  459. ```cfml
  460. component {
  461. // Properties
  462. property name="firstName";
  463. property name="lastName";
  464. property name="email";
  465. // Constructor
  466. function init( required string firstName, required string lastName ) {
  467. variables.firstName = arguments.firstName;
  468. variables.lastName = arguments.lastName;
  469. return this;
  470. }
  471. // Methods
  472. function getFullName() {
  473. return variables.firstName & " " & variables.lastName;
  474. }
  475. function setEmail( required string email ) {
  476. variables.email = arguments.email;
  477. }
  478. }
  479. ```
  480. ### Accessors
  481. ```cfml
  482. component accessors="true" {
  483. property name="firstName" type="string";
  484. property name="lastName" type="string";
  485. property name="age" type="numeric";
  486. }
  487. // Automatically generates:
  488. // - getFirstName()
  489. // - setFirstName( string firstName )
  490. // - getLastName()
  491. // - setLastName( string lastName )
  492. // - getAge()
  493. // - setAge( numeric age )
  494. ```
  495. ## Functions
  496. ### Function Declaration
  497. ```cfml
  498. // Public function
  499. function getUserById( required numeric id ) {
  500. return userDAO.find( arguments.id );
  501. }
  502. // Private function
  503. private function validateUser( required struct user ) {
  504. // Validation logic
  505. return true;
  506. }
  507. // Typed function
  508. public array function getActiveUsers() {
  509. return userDAO.findAll().filter( function( user ) {
  510. return user.active;
  511. } );
  512. }
  513. // Function with default arguments
  514. function sendEmail(
  515. required string to,
  516. required string subject,
  517. string from = "[email protected]",
  518. boolean html = true
  519. ) {
  520. // Email logic
  521. }
  522. ```
  523. ## Data Types
  524. ### Arrays
  525. ```cfml
  526. // Array creation
  527. var items = [];
  528. var numbers = [ 1, 2, 3, 4, 5 ];
  529. var users = [ { name: "Luis" }, { name: "Brad" } ];
  530. // Array methods
  531. items.append( "new item" );
  532. items.prepend( "first item" );
  533. var length = items.len();
  534. var hasItem = items.find( "value" );
  535. // Iteration
  536. items.each( function( item ) {
  537. writeOutput( item );
  538. } );
  539. // Map/Filter/Reduce
  540. var doubled = numbers.map( function( n ) { return n * 2; } );
  541. var evens = numbers.filter( function( n ) { return n % 2 == 0; } );
  542. var sum = numbers.reduce( function( acc, n ) { return acc + n; }, 0 );
  543. ```
  544. ### Structs
  545. ```cfml
  546. // Struct creation
  547. var user = {};
  548. var person = {
  549. firstName: "Luis",
  550. lastName: "Majano",
  551. age: 40
  552. };
  553. // Accessing values
  554. var name = user.firstName;
  555. var name = user[ "firstName" ];
  556. // Struct methods
  557. user.append( { email: "[email protected]" } );
  558. var keys = user.keyArray();
  559. var values = user.valueArray();
  560. var hasKey = user.keyExists( "email" );
  561. // Iteration
  562. user.each( function( key, value ) {
  563. writeOutput( "#key#: #value#" );
  564. } );
  565. ```
  566. ### Queries
  567. ```cfml
  568. // QueryExecute (modern, recommended)
  569. var qUsers = queryExecute(
  570. "SELECT * FROM users WHERE active = :active",
  571. { active: true },
  572. { datasource: "myDB" }
  573. );
  574. // Query properties
  575. var rowCount = qUsers.recordCount;
  576. var columnList = qUsers.columnList;
  577. // Query iteration
  578. for ( var row in qUsers ) {
  579. writeOutput( row.firstName & " " & row.lastName );
  580. }
  581. qUsers.each( function( row, index ) {
  582. writeOutput( row.email );
  583. } );
  584. // Query of queries
  585. var filtered = queryExecute(
  586. "SELECT * FROM qUsers WHERE age > :minAge",
  587. { minAge: 18 },
  588. { dbtype: "query" }
  589. );
  590. ```
  591. ## Control Flow
  592. ### Conditionals
  593. ```cfml
  594. // If/else if/else
  595. if ( user.active ) {
  596. sendWelcomeEmail( user );
  597. } else if ( user.pending ) {
  598. sendReminderEmail( user );
  599. } else {
  600. logInactiveUser( user );
  601. }
  602. // Ternary operator
  603. var status = user.active ? "Active" : "Inactive";
  604. // Elvis operator (null coalescing)
  605. var displayName = user.nickname ?: user.firstName;
  606. // Switch
  607. switch ( status ) {
  608. case "pending":
  609. processPending();
  610. break;
  611. case "approved":
  612. processApproved();
  613. break;
  614. case "rejected":
  615. processRejected();
  616. break;
  617. default:
  618. handleUnknown();
  619. }
  620. ```
  621. ### Loops
  622. ```cfml
  623. // For loop
  624. for ( var i = 1; i <= 10; i++ ) {
  625. writeOutput( i );
  626. }
  627. // For-in loop (arrays)
  628. for ( var item in items ) {
  629. writeOutput( item );
  630. }
  631. // For-in loop (structs)
  632. for ( var key in user ) {
  633. writeOutput( "#key#: #user[ key ]#" );
  634. }
  635. // While loop
  636. var i = 1;
  637. while ( i <= 10 ) {
  638. writeOutput( i );
  639. i++;
  640. }
  641. // Array each
  642. items.each( function( item, index ) {
  643. writeOutput( "#index#: #item#" );
  644. } );
  645. ```
  646. ## Exception Handling
  647. ```cfml
  648. try {
  649. var user = userService.getById( id );
  650. processUser( user );
  651. } catch ( EntityNotFound e ) {
  652. writeLog( type="error", text="User not found: #id#" );
  653. writeDump( e );
  654. // Handle specific exception
  655. } catch ( database e ) {
  656. writeLog( type="fatal", text="Database error: #e.message#" );
  657. // Handle database errors
  658. } catch ( any e ) {
  659. writeLog( type="error", text="Unexpected error: #e.message#" );
  660. rethrow;
  661. } finally {
  662. // Cleanup code (always executes)
  663. cleanup();
  664. }
  665. // Throw custom exception
  666. if ( !isValid( "email", email ) ) {
  667. throw(
  668. type = "ValidationException",
  669. message = "Invalid email address",
  670. detail = "Email: #email#"
  671. );
  672. }
  673. ```
  674. ## Built-in Functions (BIFs)
  675. ### String Functions
  676. ```cfml
  677. var str = "Hello World";
  678. var upper = str.ucase(); // HELLO WORLD
  679. var lower = str.lcase(); // hello world
  680. var length = str.len(); // 11
  681. var contains = str.find( "World" ); // 7
  682. var replaced = str.replace( "World", "CFML" ); // Hello CFML
  683. var trimmed = " text ".trim(); // text
  684. var split = str.listToArray( " " ); // [ "Hello", "World" ]
  685. ```
  686. ### Array Functions
  687. ```cfml
  688. var arr = [ 1, 2, 3, 4, 5 ];
  689. arr.append( 6 ); // [ 1, 2, 3, 4, 5, 6 ]
  690. arr.prepend( 0 ); // [ 0, 1, 2, 3, 4, 5, 6 ]
  691. var length = arr.len(); // 7
  692. var slice = arr.slice( 2, 4 ); // [ 1, 2, 3 ]
  693. var sorted = arr.sort( "numeric" ); // [ 0, 1, 2, 3, 4, 5, 6 ]
  694. var unique = [ 1, 2, 2, 3 ].arrayUnique(); // [ 1, 2, 3 ]
  695. ```
  696. ### Struct Functions
  697. ```cfml
  698. var user = { name: "Luis", age: 40 };
  699. user.keyExists( "name" ); // true
  700. var keys = user.keyArray(); // [ "name", "age" ]
  701. var values = user.valueArray(); // [ "Luis", 40 ]
  702. var isEmpty = user.isEmpty(); // false
  703. user.delete( "age" ); // Removes age key
  704. ```
  705. ### Date Functions
  706. ```cfml
  707. var now = now(); // Current date/time
  708. var today = dateFormat( now, "yyyy-mm-dd" );
  709. var time = timeFormat( now, "HH:mm:ss" );
  710. var tomorrow = dateAdd( "d", 1, now );
  711. var diff = dateDiff( "d", startDate, endDate );
  712. var parsed = parseDateTime( "2024-01-01" );
  713. ```
  714. ## ColdBox Handler Example
  715. ```cfml
  716. component extends="coldbox.system.EventHandler" {
  717. property name="userService" inject;
  718. property name="log" inject="logbox:logger:{this}";
  719. function index( event, rc, prc ) {
  720. prc.users = userService.getAll();
  721. event.setView( "users/index" );
  722. }
  723. function show( event, rc, prc ) {
  724. prc.user = userService.getById( rc.id ?: 0 );
  725. event.setView( "users/show" );
  726. }
  727. function save( event, rc, prc ) {
  728. try {
  729. if ( rc.id ?: 0 ) {
  730. var user = userService.update( rc.id, rc );
  731. } else {
  732. var user = userService.create( rc );
  733. }
  734. flash.put( "notice", "User saved successfully" );
  735. relocate( "users.show", { id: user.id } );
  736. } catch ( ValidationException e ) {
  737. flash.put( "error", e.message );
  738. flash.put( "data", rc );
  739. relocate( "users.edit" );
  740. }
  741. }
  742. }
  743. ```
  744. ## Service Layer Example
  745. ```cfml
  746. component singleton {
  747. property name="userDAO" inject;
  748. property name="cache" inject="cachebox:default";
  749. property name="log" inject="logbox:logger:{this}";
  750. function getAll() {
  751. return cache.getOrSet( "userList", function() {
  752. return userDAO.findAll();
  753. }, 60 );
  754. }
  755. function getById( required numeric id ) {
  756. var cacheKey = "user-#arguments.id#";
  757. return cache.getOrSet( cacheKey, function() {
  758. return userDAO.find( arguments.id );
  759. }, 30 );
  760. }
  761. function create( required struct data ) {
  762. transaction {
  763. try {
  764. var user = userDAO.create( data );
  765. cache.clear( "userList" );
  766. log.info( "User created: #user.id#" );
  767. return user;
  768. } catch ( any e ) {
  769. transaction action="rollback";
  770. log.error( "Failed to create user", e );
  771. rethrow;
  772. }
  773. }
  774. }
  775. function update( required numeric id, required struct data ) {
  776. var user = userDAO.update( arguments.id, arguments.data );
  777. cache.clear( "user-#arguments.id#" );
  778. cache.clear( "userList" );
  779. return user;
  780. }
  781. }
  782. ```
  783. ## Best Practices
  784. - **Use CFScript** over tag-based syntax for consistency
  785. - **Leverage accessors** for automatic getters/setters
  786. - **Use queryExecute()** instead of `<cfquery>` tags
  787. - **Scope all variables** explicitly (var, variables, arguments)
  788. - **Use member functions** on arrays, structs, and strings (`.map()`, `.filter()`, etc.)
  789. - **Handle exceptions** appropriately with specific catch blocks
  790. - **Use transactions** for database operations that need atomicity
  791. - **Cache expensive operations** using CacheBox
  792. - **Log important events** using LogBox
  793. - **Validate input** before processing
  794. ## Documentation
  795. For complete CFML documentation and built-in functions, visit:
  796. - https://cfdocs.org
  797. - https://modern-cfml.ortusbooks.com
  798.  
  799.  
  800. ## AI Integration & Resources
  801.  
  802. This project includes AI-powered development assistance with on-demand guidelines, skills, and MCP documentation servers.
  803.  
  804. ## Project-Specific Conventions
  805.  
  806. ### Code Style
  807.  
  808. - **Semicolons:** Optional in CFML/BoxLang. Only use when demarcating properties or in inline component syntax
  809. - **Handler naming:** Plural nouns (Users.cfc, Orders.cfc)
  810. - **Service naming:** Descriptive with "Service" suffix (UserService.cfc)
  811. - **Dependency injection:** Use `property name="service" inject` over manual getInstance()
  812.  
  813. ### Testing
  814.  
  815. - Tests located in `/tests/specs/`
  816. - Integration tests extend `BaseTestCase` with `appMapping="/app"`
  817. - **Critical:** Always call `setup()` in `beforeEach()` for test isolation
  818. - Run tests: `box testbox run`
  819.  
  820. ### Configuration
  821.  
  822. - Environment variables defined in `.env` (copy from `.env.example`)
  823. - Access via `getSystemSetting("VAR_NAME", "default")`
  824. - Framework config in `config/ColdBox.cfc`
  825. - Routes in `config/Router.cfc`
  826.  
  827. ### Application Helpers
  828.  
  829. - `includes/helpers/ApplicationHelper.cfm` - Available in all handlers/views
  830. - Add common utility functions here
  831.  
  832. ### Development Workflow
  833.  
  834. ```bash
  835. # Install dependencies
  836. box install
  837.  
  838. # Start server
  839. box server start
  840.  
  841. # Format code
  842. box run-script format
  843.  
  844. # Run tests
  845. box testbox run
  846.  
  847. # Reinit framework (dev)
  848. /?fwreinit=true
  849. ```
  850.  
  851. ## AI Integration
  852.  
  853. This project includes AI-powered development assistance with guidelines, skills, and MCP documentation servers.
  854.  
  855. ### Directory Structure
  856.  
  857. ```
  858. /.ai/
  859. /manifest.json - AI configuration (language, agents, guidelines, skills, MCP servers)
  860. /guidelines/ - Framework documentation and best practices
  861. /core/ - Core ColdBox/BoxLang guidelines
  862. /modules/ - Module-specific guidelines
  863. /custom/ - Your custom guidelines
  864. /overrides/ - Override core guidelines
  865. /skills/ - Implementation cookbooks (how-to guides)
  866. /core/ - Core development patterns
  867. /modules/ - Module-specific patterns
  868. /custom/ - Your custom skills
  869. /overrides/ - Override core skills
  870. /mcp-servers/ - MCP server configurations
  871. ```
  872.  
  873. ### Manifest
  874.  
  875. The `.ai/manifest.json` file contains the complete AI integration configuration:
  876.  
  877. - **language**: Project language mode (boxlang, cfml, hybrid)
  878. - **templateType**: Application template (modern, flat)
  879. - **guidelines**: Array of installed guideline names
  880. - **skills**: Array of installed skill names
  881. - **agents**: Array of configured AI agents
  882. - **mcpServers**: Configured MCP documentation servers (core, module, custom)
  883. - **activeAgent**: Currently active AI agent (if set)
  884. - **lastSync**: Last synchronization timestamp
  885.  
  886. **Reading the manifest** helps you understand available resources and project configuration.
  887.  
  888. ### Using Guidelines & Skills
  889.  
  890. **Core framework guidelines (ColdBox and language) are already included above.** Additional guidelines and all skills are available on request:
  891.  
  892. - **Module Guidelines** provide documentation for installed ColdBox modules
  893. - **Skills** offer step-by-step implementation patterns for specific features
  894. - Request specific guidelines or skills by name when you need them
  895.  
  896. ### Available Guidelines
  897.  
  898. The following additional guidelines are available for this project. Request them by name when needed:
  899.  
  900.  
  901.  
  902. **To load a guideline:** Request it by name when you need detailed framework or module documentation.
  903.  
  904. ### Available Skills
  905.  
  906. The following skills provide step-by-step implementation patterns. Request specific skills when you need detailed how-to instructions:
  907.  
  908. **Core Skills (Available on request):**
  909.  
  910. - **handler-development** - Implementation patterns for ColdBox handler development including CRUD operations, dependency injection, and event handling
  911. - **rest-api-development** - Build RESTful APIs in ColdBox with proper HTTP methods, validation, error handling, and API best practices
  912. - **module-development** - Create reusable ColdBox modules with proper structure, configuration, and integration patterns
  913. - **interceptor-development** - Build ColdBox interceptors for cross-cutting concerns, event listening, and aspect-oriented programming
  914. - **routing-development** - Configure ColdBox routes, RESTful resources, route groups, and advanced routing patterns
  915. - **event-model** - Master the ColdBox request context object for handling requests, responses, and application flow control
  916. - **view-rendering** - Advanced view rendering techniques including partials, caching, helpers, and dynamic content generation
  917. - **layout-development** - Create and manage ColdBox layouts and views with proper rendering, helpers, and dynamic content
  918. - **cache-integration** - Implement caching strategies using CacheBox for improved application performance and scalability
  919. - **cfml-development** - Reusable starter for authoring high-quality skills with clear trigger phrases, implementation steps, testing expectations, and framework-aligned coding conventions.
  920. - **testing-bdd** - Practical guide to TestBox BDD workflows, including spec structure, readable scenario naming, expectation style, setup/teardown patterns, and maintainable behavior-focused tests.
  921. - **testing-unit** - Comprehensive guide to writing unit tests with TestBox, including test organization, assertions, expectations, data providers, and testing best practices for isolated component testing
  922. - **testing-integration** - Comprehensive guide to integration testing in ColdBox applications, including database integration, API testing, external service integration, and full-stack testing strategies
  923. - **testing-handler** - Comprehensive guide to testing ColdBox event handlers, including request context mocking, event execution, HTTP method testing, and validation testing for controllers
  924. - **testing-mocking** - Complete guide to mocking dependencies in tests using MockBox, including creating mocks, stubs, spies, and verification patterns
  925. - **testing-fixtures** - Comprehensive guide to test data management including fixtures, factories, seeders, and data builders for consistent and maintainable test data
  926. - **testing-coverage** - Complete guide to code coverage analysis in CFML/BoxLang applications, including coverage metrics, reporting, CI integration, and improving test coverage
  927. - **testing-ci** - Complete guide to setting up continuous integration for automated testing, build pipelines, deployment workflows, and CI best practices
  928.  
  929.  
  930. **To load a skill:** Request it by name when implementing specific features or patterns.
  931.  
  932. ## Important Notes
  933.  
  934. - Framework reinit: Use `?fwreinit=true` or configure `reinitPassword` for production
  935. - Module routes process before app routes - be aware of conflicts
  936. - Use PRC for internal data, RC only for user input
  937. - Always validate user input from RC
  938.  
  939. ## MCP Documentation Servers
  940.  
  941. This project has access to the following Model Context Protocol (MCP) documentation servers for live, up-to-date information:
  942.  
  943. **Core Documentation Servers:**
  944.  
  945. - **boxlang**: BoxLang Language Documentation - https://ai.ortusbooks.com/~gitbook/mcp
  946. - **coldbox**: ColdBox Framework Documentation - https://coldbox.ortusbooks.com/~gitbook/mcp
  947. - **commandbox**: CommandBox CLI Documentation - https://commandbox.ortusbooks.com/~gitbook/mcp
  948. - **testbox**: TestBox Testing Framework - https://testbox.ortusbooks.com/~gitbook/mcp
  949. - **wirebox**: WireBox Dependency Injection - https://wirebox.ortusbooks.com/~gitbook/mcp
  950. - **cachebox**: CacheBox Caching Framework - https://cachebox.ortusbooks.com/~gitbook/mcp
  951. - **logbox**: LogBox Logging Framework - https://logbox.ortusbooks.com/~gitbook/mcp
  952.  
  953. **Module Documentation Servers:**
  954.  
  955. - **cbsecurity**: CBSecurity Authentication/Authorization - https://coldbox-security.ortusbooks.com/~gitbook/mcp
  956. - **cbvalidation**: CBValidation Validation Framework - https://coldbox-validation.ortusbooks.com/~gitbook/mcp
  957. - **quick**: Quick ORM Active Record - https://quick.ortusbooks.com/~gitbook/mcp
  958. - **cbmailservices**: CBMailServices Email Integration - https://coldbox-mailservices.ortusbooks.com/~gitbook/mcp
  959. - **relax**: Relax REST API Documentation - https://coldbox-relax.ortusbooks.com/~gitbook/mcp
  960.  
  961. **Using MCP Servers:** Query these servers when you need current documentation, API references, or code examples. They provide live, up-to-date information directly from official documentation sources.
  962.  
  963. ## Additional Resources
  964.  
  965. - ColdBox Docs: https://coldbox.ortusbooks.com
  966. - TestBox: https://testbox.ortusbooks.com
  967. - WireBox: https://wirebox.ortusbooks.com
  968.  
  969. <!-- COLDBOX-CLI:END -->
  970.  
  971. <!-- ℹ️ YOUR PROJECT DOCUMENTATION — Add your custom details below. ColdBox CLI will NOT overwrite this section. -->
  972.  
  973. ## Custom Application Details
  974.  
  975. <!-- Add project-specific information below -->
  976.  
  977. ### Business Domain
  978.  
  979. <!-- Describe what this application does -->
  980.  
  981. ### Key Services/Models
  982.  
  983. <!-- List important services and their responsibilities -->
  984.  
  985. ### Authentication/Security
  986.  
  987. <!-- Describe authentication approach if applicable -->
  988.  
  989. ### API Endpoints
  990.  
  991. <!-- Document REST API routes if applicable -->
  992.  
  993. ### Deployment
  994.  
  995. <!-- Document deployment process -->
  996.  
  997. ### Third-Party Integrations
  998.  
  999. <!-- List external services, APIs, or integrations -->
  1000.  
Advertisement
Comments
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
Add Comment
Please, Sign In to add comment