2011-09-07 110 views
2

我想創建一個方法,可以修改文件中的類並將類轉儲到同一個文件。修改一個類並拋棄它的好方法? - 反思?

這樣做的最佳做法是什麼?

我所試圖做的是:

說我有類:

test.php的:

namespace test; 
class Test{ 

} 

...,我想處理此所以最終的輸出將是

Test.php:

namespace test; 
class Test implements /interfaces/Entity{ 

} 

帶* str_replace函數*它會是這樣的:

function parseImplementation($src, $class, $interface){ 
    return str_replace("$class", " $class implements $interface", $src); 
} 

我已經試過反射API,但我真的不能找到一種方法來編輯類本身和它轉儲到源代碼。

有沒有這樣做的任何順利的方式? str_replace不是一個選項,因爲Test類可以實現其他的東西,並用製表符/空格鍵入分隔符。

+0

看起來像你想對一個類文件做RAW更新? – ajreal

+0

不能決定是否只是相關或可能重複:[自動生成PHP代碼的策略?](http://stackoverflow.com/questions/1979545/strategy-to-auto-generate-php-code/1979600#1979600)和[創建-php文件與內容從終端](http://stackoverflow.com/questions/2153276/create-php-file-with-content-from-terminal) – Gordon

+0

我真的第一個問「爲什麼?'並且說'這個主意不好。'? – Rudie

回答

1

你想要的是一個source-to-source program transformation system。這是一種將代碼解析爲獨立於佈局等的編譯器數據結構(抽象語法樹)的工具,然後讓您編寫「如果您看到然後將其替換爲」操作,即對編譯器數據結構進行操作。 (是的,你可以試着用字符串黑客來做這件事,它可能適用於你手中的例子,但是字符串黑客通常是不可靠的,因爲你不能只用字符串黑客來解析真實源代碼)。

爲此,您需要一些可以可靠地解析PHP並將源應用於源變換的東西。現有的工具並不多。

我們的DMS Software Reengineering Toolkit及其PHP Front End是一個可以。

你特定的轉換可以這樣做與DMS:

domain PHP~PHP5; -- declare the programming language DMS will process 

    rule add_interface_to_class(class_name:identifier, 
           m: class_members): 
      class_declaration -> class_declaration = 
    "class \i { \m } " 
    -> "class \i implements /interfaces/\entity\(\){ \m } "; 

    rule add_another_interface_to_class(class_name:identifier, 
             ifaces:interfaces, 
             m: class_members): 
      class_declaration -> class_declaration = 
    "class \i implements \ifaces { \m } " 
    -> "class \i implements \ifaces,/interfaces/\entity\(\){ \m } "; 

我有兩個規則在這裏,一到處理您的類有implements子句, 和一個前來處理的情況下的工具子句已經存在。

目前尚不清楚「namespace test」如何在您的示例中起作用,但如果這很重要,則必須爲每個規則添加條件測試,以驗證標識符位於「正確」命名空間中。

相關問題