I'm prototyping behaviour of a new application, and want to write some functions that check on access based on some variable dates.
I just want to write seperate functions for that, like "canUserSeeThis()" and "canUserSeeThat()"
In case one of these returns false, I want to display a message, but I want that message to be defined in these functions, but the rendering taking part outside the functions.
What is the best "pattern" to quickly build such a functionality? Should I let the message be in the return value? Should I work with throwing exceptions?
I'm just prototyping, so I don't want to end up defining a complete API system yet.
I think that just passing by reference is what you need:
<?php
function canUserSeeThis(&$whyCanNotMessage)
{
$whyCanNotMessage = 'Because you are not administrator';
return false;
}
$meesage;
if (!canUserSeeThis($meesage))
print($message);
?>
If you need to gather several messages you could pass by reference an array and every canUserSeeXXX() method will add a string to the array. Later you print all array items to the user.
<?php
function canUserSeeThis(&$whyCanNotMessageList)
{
array_push($whyCanNotMessageList, 'Because you are not administrator');
return false;
}
function canUserSeeThat(&$whyCanNotMessageList)
{
array_push($whyCanNotMessageList, 'Because you are not advanced user');
return false;
}
$meesageList = array();
$shouldShowMessage = !canUserSeeThis($meesageList)||!canUserSeeThat($meesageList);
if ($shouldShowMessage)
echo '<pre>'; print_r($meesageList); echo '</pre>';
?>