我想根据数据库表中的数据创建一些路由。我假设这需要在框架初始化之后完成,所以我目前所做的是创建一个新的拦截器,它运行在:
afterConfigurationLoad
.
addRoute()
我一出错
Variable ADDROUTE is undefined.
所以我想
添加路由()
以下是我的拦截器中的一些示例代码:
component {
property name="myService" inject="myService"; // injects my model which will get some data
/**
* afterConfigurationLoad
* Runs after the framework configucation loads
*/
void function afterConfigurationLoad( event, interceptData, buffer, rc, prc ){
// get some data which will be converted into routes
var myDataList = myService.list();
// loop through the data
for ( var data in myDataList ) {
// add our route. NOTE: I'll also want to populate the prc scope with a value
addRoute( pattern="/#data.slug#", handler="data", action="index" );
}
}
}
编辑1:使用ColdBox v5.1.1
布拉德的回答使我走上了正轨。我无法在拦截程序中注入路由器,因为它生成了一个错误。但是,我可以使用
getInstance( "router@coldbox" )
然后打电话
route()
重要:
默认情况下,路由会附加到路由表中。如果你想让他们工作,你可能需要预先准备好路线。
解决方案1:
component {
property name="myService" inject="myService"; // injects my model which will get some data
/**
* afterConfigurationLoad
* Runs after the framework configucation loads
*/
void function afterConfigurationLoad( event, interceptData, buffer, rc, prc ){
// instance the router
var router = getInstance( "router@coldbox" );
// get some data which will be converted into routes
var myDataList = myService.list();
// loop through the data
for ( var data in myDataList ) {
// prepend our route
router.route( "/#data.slug#" ).prcAppend( { id : #data.id# } ).to( "data.index" ).prepend();
}
}
}
此外,可能有一种更简单的方法来解决这个问题,方法是将模型服务注入到“config/router.cfc”配置文件中,然后添加任何动态路由。
解决方案2:
component {
property name="myService" inject="myService"; // inject the model
function configure() {
setFullRewrites( true );
// get the data I need from the model for dynamic routes
var myDataList = myService.list();
// loop through the data
for ( var data in myDataList ) {
// add the dynamic route
router.route( "/#data.slug#" ).prcAppend( { id : #data.id# } ).to( "data.index" );
}
route( ":handler/:action?" ).end();
}
}
解决方案3:
事实证明,当框架初始化时,拦截器首先被加载,所以并不是所有依赖项都可用。Brad建议在属性中使用提供程序命名空间,这也是一个可接受的解决方案。
component {
property name="myService" inject="myService"; // injects my model which will get some data
property name="router" inject="provider:router@coldbox";
/**
* afterConfigurationLoad
* Runs after the framework configucation loads
*/
void function afterConfigurationLoad( event, interceptData, buffer, rc, prc ){
// get some data which will be converted into routes
var myDataList = myService.list();
// loop through the data
for ( var data in myDataList ) {
// prepend our route
router.route( "/#data.slug#" ).prcAppend( { id : #data.id# } ).to( "data.index" ).prepend();
}
}
}