[英]Better management of “messages” between function?
在我的框架中,我有一些功能,完成后它們可以將一些消息添加到隊列中進行報告。
示例:我有一個功能,可以拍攝照片並
我有一個全局$msgQueue=array();
每當頁面的所有邏輯都完成時,在我的模板中,我便向用戶回顯所有報告(這些功能可以在執行期間添加)。
在這種情況下,會將2條消息添加到$ msgQueue中:
但是我認為這種行為不是標准的。 如果我想與某人共享我的函數之一(在這種情況下為checkImage($path)
),則該函數將無法正常工作,因為函數需要該全局數組來放置其報告消息。
是否有解決此問題的標准方法,以便我可以與他人共享我的功能,而不必擔心這種依賴性?
我的建議是使用一個類,例如:
class Report(){
public $msgQueue;
function addReport($string){
array_push($this->msgQueue, $string); //store new report
}
function showReports(){
//loop over the message queue
...
}
}
好處:
您可以使用同一類創建不同類型的報告,將過程與錯誤分開,例如, $processes = new Report
和$errors = new Report
無需將vars聲明為全局變量,該類保留其屬性$msgQueue
的值,您只需要$processes->addReport("Resizing image to XXX")
OOP的好處,具有邏輯結構等
我真的不認為有一種標准的方法。 我的工作是這樣的:
給每個庫(圖像,文件等)自己的消息數組。
使用具有自己的消息數組以及可以通過Message::addSource($class, $propertyName)
構建/添加的“源”數組的消息庫。 (我在創建庫實例(例如Image)后立即添加了消息源)。
這樣,每個庫都可以獨立於其他庫,同時仍然可以具有每個實例和全局消息數組。
是否有解決此問題的標准方法?
是的,它稱為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.