簡體   English   中英

更好地管理功能之間的“消息”?

[英]Better management of “messages” between function?

在我的框架中,我有一些功能,完成后它們可以將一些消息添加到隊列中進行報告。

示例:我有一個功能,可以拍攝照片並

  • 如果圖像不是.jpg,則將其轉換為.jpg
  • 如果圖像大於500kB,則會減小其大小

我有一個全局$msgQueue=array(); 每當頁面的所有邏輯都完成時,在我的模板中,我便向用戶回顯所有報告(這些功能可以在執行期間添加)。

在這種情況下,會將2條消息添加到$ msgQueue中:

  • 圖片為PNG,已轉換為JPG
  • 圖片為2000x1000,現在為1000x500

但是我認為這種行為不是標准的。 如果我想與某人共享我的函數之一(在這種情況下為checkImage($path) ),則該函數將無法正常工作,因為函數需要該全局數組來放置其報告消息。

是否有解決此問題的標准方法,以便我可以與他人共享我的功能,而不必擔心這種依賴性?

我的建議是使用一個類,例如:

class Report(){
    public $msgQueue;

    function addReport($string){ 
         array_push($this->msgQueue, $string);  //store new report
    }

    function showReports(){
         //loop over the message queue
         ...
    }
}

好處:

  1. 您可以使用同一類創建不同類型的報告,將過程與錯誤分開,例如, $processes = new Report$errors = new Report

  2. 無需將vars聲明為全局變量,該類保留其屬性$msgQueue的值,您只需要$processes->addReport("Resizing image to XXX")

  3. OOP的好處,具有邏輯結構等

我真的不認為有一種標准的方法。 我的工作是這樣的:

  • 給每個庫(圖像,文件等)自己的消息數組。

  • 使用具有自己的消息數組以及可以通過Message::addSource($class, $propertyName)構建/添加的“源”數組的消息庫。 (我在創建庫實例(例如Image)后立即添加了消息源)。

    • 執行Message :: render()時,它將每個源的消息與Message類自己的消息組合在一起,然后呈現它們。

這樣,每個庫都可以獨立於其他庫,同時仍然可以具有每個實例和全局消息數組。

是否有解決此問題的標准方法?

是的,它稱為OOP :)(有關此信息,請參見amosrivera的答案)。

但是,如果OOP不是一個選項(但是您仍然應該認真考慮),則可以重構函數以接受messageQueue參數(並通過引用傳遞它)。

// passing $messageQueue by reference by prepending &
function checkImage( $path, array &$messageQueue = null )
{
    /* do image checking */
    $result = /* the result of the image checking */;

    // if $messageQueue argument is provided
    if( $messageQueue !== null )
    {
        // add the message to the queue
        $messageQueue[] = 'Image checking done';
    }

    return $result; // false or true perhaps.
}

用法:

$messageQueue = array();

if( checkImage( $somePath, $messageQueue ) )
{
    echo 'checking image succeeded';
}
else
{
    echo 'checking image failed';
}

var_dump( $messageQueue );

// would output something like:
Array(1) (
    'Image checking done'
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM