2014-10-07 77 views
0

我想在Zend2 MVC框架中包裝遺留應用程序。感謝Zend Skeleton Application和代碼示例(特別是https://github.com/maglnet/MaglLegacyApplication),我已經解決了我的大部分問題。Zend 2進口和全局命名空間

的一個大問題,我一直沒能解決由下面的「遺產」的文件所示:

<?php 
$test = "test"; 

function echo_test(){ 
     global $test; 
     echo "test = "; 
     var_dump($test); # Makes NULL explicit 
} 

echo_test(); 

在控制器的ZF2模塊,我捕捉到的包括使用輸出輸出緩衝器,並堅持認爲到響應對象:

... 
chdir($filePath) # Fixes relative includes 
ob_start(); 
include $filePathAndName; 
$output = ob_get_clean(); 
$response->setContent($output); 
return $response; 

...我回來test = NULL

我見過警告說ZF2命名空間可以爲遺留文件創建問題,並完成我的工作來嘗試澄清原因。根據PHP指南,"Without any namespace definition, all class and function definitions are placed into the global space"。事實上,我的樣本只比本文下面列出的樣本稍微複雜一些......但似乎並不奏效。

我也看到「You can set a variable after declaring a namespace, but variables will always exist in the global scope. They are never bound to namespaces.」。

我繼續研究,終於發現這種方法「will import the contents of the include file into the method scope, not the class scope」。

有沒有辦法在方法範圍之外處理文件?

回答

0

這與PHP命名空間無關。如果您在ZF控制器操作中包含文件,它將在該函數的變量範圍內執行。作爲你的榜樣,你需要在包括文件之前在ZF行動中聲明global $test;(這會很糟糕)。

不知道你的遺留代碼是什麼樣子,很難提出一個好的解決方案。如果有一定數量的全局變量需要工作,則可以在ZF應用程序的某個時間點將它們全局化(以便在日後刪除該變更)。如果您事先不知道全局變量是什麼,或者有大量變量,您可能需要編輯遺留代碼以嘗試重構對全局變量的依賴。

+0

燁(可以被解析)。我終於達到了同樣的結論。全球範圍內有近700個獨特的變量可供使用。儘管它很糟糕,但它很快就會grep,刪除重複項,並將它們全部整合到一起。 – claytond 2014-10-08 02:27:04