2016-04-02 72 views
0

在我的應用程序中,我實例化了一個名爲controller的應用程序範圍對象。另外,我正在啓動一臺服務器。由於我想保持冗餘低,每個請求我想實例化一個前端controller,這是一個複製/參考controller,但與另一個pool財產,其中包含請求寬對象/配置,可以從controller定義具有其他上下文特定屬性的引用

var applicationPool = new ObjectPool(); // container for objects 
var controller = new Controller(); // application wide instance 
var server = http.createServer(); 

applicationPool.set("myController", controller); 

server.on("request",function(req,res){ 
    var requestPool = new ObjectPool(); 

    requestPool.set("request",req); 
    requestPool.set("response",res); 

    /* 
    * pool population 
    * routing 
    * controller resolving 
    * parameter resolving 
    */ 

    // frontend specific to current request 
    var frontend = applicationPool.get("myController").create(requestPool); 

    // hopefully finishes res 
    frontend.greetAction(parameters); 

    /* 
    * post response actions 
    */ 
} 

server.listen(3000); 

而且Controller類:

function Controller(){ 
    BaseController.call(this); 
    // ... 
} 

function greetAction(parameters){ 
    var res = this.getObjectPool().get("response"); // defined in BaseController 
    res.end(format("Greetings, %s!",parameters["name"])); 
} 

Controller.prototype = Object.create(BaseController.prototype); 
Controller.prototype.greetAction = greetAction; 

附加我約BaseController類的想法:

function BaseController(){ ... } 

function getObjectPool(){ 
    return this.pool; 
} 

function create(pool){ 
    var frontend = Object.create(this.__proto__, this); 
    frontend.pool = pool; 
    return frontend; 
} 

BaseController.prototype.getObjectPool = getObjectPool; 
BaseController.prototype.create = create; 

這是我被困。對於我測試的。如果我將pool添加到frontend它也適用於controller對象。我正在考慮創建一個新對象並追加controller的所有屬性。我還看了一下代理,controller作爲目標,get陷阱爲getObjectPool

我知道直接修改res是不好的做法。相反,我可能會返回string/buffer。但所描述的問題仍然存在。正如我計劃嵌入其他控制器。

我來自PHP + Symfony,你有一個Controller類與getContainer方法和核心對象的快捷方式,做同樣的事情。

任何想法表示讚賞。有一段時間我正試圖解決這個問題。

乾杯!

回答

0

好吧我想我有一個解決方案。這有點棘手,因爲我實際上將所有「受保護」數據保存在"__"屬性(this.__.pool)中。下面是在該示例中,工作create功能的代碼:

function create(pool){ 
    return new Proxy(this,{ 
     get: function(target, property){ 
      if(property === 'pool') return pool; 
      return target[property]; 
     } 
    }); 
} 

這將返回一個代理(frontend)爲controller。每當我訪問frontendpool,調用者將被重定向到分配的pool參數。即使在frontend對象內。

//... 
var frontend = applicationPool.get("myController").create(requestPool); 
frontend.greetAction(parameters); // this.pool will be redirected to requestPool 
//... 

我會等待其他建議,我檢查之前解決。

相關問題