2012-05-21 138 views
2

我有一個運行一些相當通用的代碼的功能,這些代碼可以很多工作連接到數據庫並設置不同的配置變量。讓我們不要涉及這個道德問題,請和我一起裸露。我有幾個這樣的頂級函數代碼的聲明,我運行它實際上是不同的函數。創建函數接受函數

這就是它現在的樣子。

function get_users(){ 
    // config 
    // set application keys 
    // connect to database 
    // retrieve user data 
    // authentication to foreign api 
    if(something){ 
    // some more red-tape 
    if(something){ 
     //more more 
     if(something){ 
     /* finally the good stuff */ 

     // the code here varies from function to function 
     // eg. get users 
     // probably will run: inner_get_users(); 

     } 
    } 
    } 
} 

function get_data(){ 
    // config 
    // set application keys 
    // connect to database 
    // retrieve user data 
    // authentication to foreign api 
    if(something){ 
    // some more red-tape 
    if(something){ 
     //more more 
     if(something){ 
     /* finally the good stuff */ 

     // the code here varies from function to function 
     // eg. get data 
     // probably will run: inner_get_data(); 

     } 
    } 
    } 
} 

如何我希望它的工作,可能使用匿名函數:

function instance($inner){ 
    // config 
    // set application keys 
    // connect to database 
    // retrieve user data 
    // authentication to foreign api 
    if(something){ 
    // some more red-tape 
    if(something){ 
     //more more 
     if(something){ 
     /* finally the good stuff */ 

     Call inner 

     } 
    } 
    } 
} 

function get_data(){ 

    instance(function(
    // get the data 
)); 

} 

也許

function get_users(){ 

    $var = function(
    // get the users 
); 

    instance($var); 

} 

我在尋找更好的,烘乾機,以及更易於維護的代碼。

+0

您可能正在尋找一個回調[call_user_func](http://php.net/manual/en/function.call-user-func.php)? –

回答

1

這是PHP調用variable functions的東西。當$inner是一個函數的字符串名稱,當它是一個anonymous function(儘管變量函數的手冊頁不能解釋這個)時,這兩個函數都起作用。

function instance($inner){ 
    // config 
    // set application keys 
    // connect to database 
    // retrieve user data 
    // authentication to foreign api 
    if(something){ 
    // some more red-tape 
    if(something){ 
     //more more 
     if(something){ 
     /* finally the good stuff */ 

     return $inner(); 

     } 
    } 
    } 
} 
+0

-1你總是想在調用它之前檢查函數是否存在。 – iambriansreed

+0

iambriansreed,不,不總是。這取決於你如何處理錯誤和你的防守編碼方法。如果你做錯了什麼,你會讓事情失敗,因爲我更喜歡積極的編碼,因爲這樣更容易排除故障。 –

+0

「最好是要求原諒而不是許可」,@EmilVikström這是一種非常積極的編碼風格,也許是一個try-catch塊來捕獲任何異常,而不是使用set_error_handler函數,這爲我們編碼恕我直言編碼提供了更多的靈活性。 –