Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
What is preferable: A function that decides itself if it should do anything, or deciding whether to call that function?
function x() {
if ($userIsLoggedIn) {
alwaysHelloUser();
}
if ($visitorRegion != 'US') {
alwaysDisplayNoInternationalShipping();
}
if ($day == 'Sunday') {
alwaysLockDownStore();
}
}
function alwaysLockDownStore() {
//close store
//offer alternative store
//show opening hours
//display form for user leaving order for next day
exit("Sorry, we are closed!");
}
or
function y() {
perhapsSayHelloUser($user);
maybeDisplayNoInternationalShipping($region);
sometimesLockDownStore($day);
}
function sometimesLockDownStore($day) {
if ($day == 'Sunday') {
//close store
//offer alternative store
//show opening hours
//display form for user leaving order for next day
exit ("Sorry, we are closed!");
}
}
The example is trivial, but imagine enabling functions using configuration or access rights. Is there an accepted standard? My gut tells me to go for y() when there is something like exit() involved, breaking the normal flow. Otherwise, encapsulation and DRY would favor x(). What do you think?
Edit I've expended the example. My question is really: If there is a condition on which a function/method should be executed, should that control take place in the function (tidy but outcome is uncertain) or outside it (calling is verbose, but expected output is always the same)?
I'd prefer to keep the main functionality in the function. Extra logic outside. Because the function will do just that what is intented. Or you would everytime run the function needed or not. Depending how complex your problem will be.
function lockStoreOnDay($day) {
// do locking
return "Sorry, we are closed on $day!";
}
echo lockStoreOnDay('Sunday'); //will print "Sorry, we are closed on Sunday!"
echo lockStoreOnDay('Saturday'); //will print "Sorry, we are closed on Saturday!"
Generally: Why not use a Class?
If you have access rights or a configuration this information could be stored in an Array or Object. So you iterate through the Array or search for your keyword and than process whatever should be processed. I. e. make a function call.
function lockStoreOnDay()
{
//do locking
return "Sorry, we are closed!";
}
$config_closeOnDay = array (
'Sunday'
);
foreach ($config_closeOnDay as $dayToCloseOn) {
echo lockStoreOnDay();
}
Maybe this helps.
You shouldn't have such constraints hardcoded inside function. You should aim for something like:
function isStoreLocked($dayToCheck, $daysLocked)
{
// You can replace "locking" logic with database or something
// There shouldn't be an raw array of days inside code
return in_array($dayToCheck, $daysLocked);
}
Then in your code:
$curentDayName = date('l');
$lockedDays = array('Saturday', 'Sunday');
if(isStoreLocked($currentDayName, $daysLocked))
{
die('Sorry, store is locked!');
}
To give context to my answer: if you do it using a framework (my choice is Symfony2) isStoreLocked should be a service or a repository method and it should be called inside controller while returning Response (rather than simple die()).
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
So im grabbing data from a json APi, and using a foreach to echo it out into complex links. Lets say the data includes
-title
-link
-image
So the first foreach would loop through the data and echo it out in a format, with the image thumbnail, and the title clickable, all wrapped in a block.
Then, somewhere else in the site, I need to work with the same data, but in different formats, and I wanted to see if I could do this without using multiple foreachs everywhere.
First I need to check if a title is available, and return either true or false,
Then I need to list out the titles again, this time as plain text, separated by a comma, and excluding the one I already checked.
Not sure if that makes sense but the code would look something like this
<?php
$neflix = false;
$hulu = false;
$amazon = false;
foreach($sources as $source) {
if ($source['source'] == "netflix"){$neflix = true;}
if ($source['source'] == "hulu"){$hulu = true;}
if ($source['source'] == "amazon"){$amazon= true;}
echo '<a href="'.$source['link'].'" class="streaming-option">
<img src="'. get_stylesheet_directory_uri()."/assets/images/sources/78x78/".$source['source'].'".png"/>
<strong>'. $source['display_name'] .'</strong>
</a>';
}
That's what I have so far for the first loop. I declared the initial titles outside the foreach loop so I can use them later elsewhere I the code, and then check if they exist inside of the loop, and set it to true if they do.
So I'm just wondering if I would need to set up a completely different foreach loop, if I wanted to simply list out the same titles in text format in another section, separated by comma, instead of a full link, and excluding a source in each of them (I would have to create a comma separated list for each one, the hulu and netflix and amazon in the example above)
Im thinking the second part would look like this
<?php
if($netflix == true) {
echo "Yes, Netflix is available, it is also available in ";
foreach($sources as $source) {
if ($source['source'] != "netflix") {
echo $source['display_name'].", ";
}
}
}
And do the same for Hulu, amazon, etc. I'm really hoping there's a cleaner way to do that.
You can collect the data you need in a variable then echo the variable into the desired section.
I'm going to try to use your code.
<?php
$neflix = false;
$hulu = false;
$amazon = false;
$holderNetflix = [];
$holderHulu = [];
$holderAmazon = [];
foreach($sources as $source) {
if ($source['source'] == "netflix"){
$neflix = true;
array_push($holderNetflix,$source['display_name']); // collecting data
}
if ($source['source'] == "hulu"){
$hulu = true;
array_push($holderHulu,$source['display_name']);
}
if ($source['source'] == "amazon"){
$amazon= true;
array_push($holderAmazon,$source['display_name']);
}
echo '<a href="'.$source['link'].'" class="streaming-option">
<img src="'. get_stylesheet_directory_uri()."/assets/images/sources/78x78/".$source['source'].'".png"/>
<strong>'. $source['display_name'] .'</strong>
</a>';
}
You can now use the holder variable and implode the array to print the list
echo implode(",", $holderNetflix);
echo implode(",", $holderHulu);
echo implode(",", $holderAmazon);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi guys i'm having a small issue when i try and convert my exisiting script into a simple function. I'll leave my code below.
PHP:
function service_check($postcode) {
$op_postcodes = array(... "DG10","DG3","DG4" ...);
if(isset(htmlentities($postcode))) {
$postcode_checker = trim(strtoupper(htmlentities($postcode)));
$trim_postcode = trim(substr(htmlentities($postcode_checker, 0, -3)));
if(empty($postcode_checker)) {
$error = "We require your postcode to check our service in your area.";
} else if(!valid_postcode($postcode_checker)) {
$otp = "The postcode you entered is invalid.";
} else if(!in_array($trim_postcode, $op_postcodes)) {
$otp = "Sorry, but we don't provide our service's in your area, just yet.";
} else {
$otp = "Great news! We're in your area and you are eligible to order our services!";
$_SESSION['customer_postcode'] = $postcode_checker;
}
} else {
$otp = "To get started please enter your postcode.";
}
}
My current usage of the function is <?php service_check($_POST['service_check']); ?>
My error is:
Fatal error: Cannot use isset() on the result of a function call (you can use "null !== func()" instead) in /home/domain.com/public_html/controller/application/functions/locale.SM.php on line 27
change this
if(isset(htmlentities($postcode))) {
to this
$pc = htmlentities($postcode);
if(isset($pc)) {
read this if you get sometime - http://php.net/manual/en/function.isset.php http://php.net/manual/en/function.htmlentities.php
Since your questions wasn't complete i assume so now an edit. The better approach could be to use !empty() instead of isset() on our if condition.
Even better, reove htmlentities method call from your if block and then later use html entities when you actually need it.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a php file which basically reads a page using JSON and a variable is returned to it (pending/paid/expired). now my simple requirement is if the returned variable is paid/expired the respective actions for them should be taken and the loop should not be repeated but if the response is pending the code should recheck after 10 seconds. A similar cycle then happens again and so on till the loop is stopped(by receiving either a expired/paid response.
here is the code i prepared for it using the examples i found at various places but this doesnt seem to work correctly.. pls guide..
while($end==0) {
$json = file_get_contents('http://old.kbourbaki.com/xlisteningpageprestashop.aspx?yyyyyyy');
$obj = json_decode($json);
$result=$obj->response;
echo($result);
if ($result=='paid') {
p('Order Successfull');
$end=1;
} elseif ($result=='expired' ) {
p('status = expired');
$end=1;//ex
} else {
d('status = Pending');
sleep(10);
}
}
CODE UPDATED extra '{' removed
You have one too many curly braces.
The proper elseif and else block should look like this
} elseif ($result=='expired' ) {
p('status = expired');
$end=1;//ex
} else {
It would help you a lot if you properly formatted your code.
You close the IF condition before the last ELSE just delete the closing clasp.
if($result=='paid'){
p('Order Successfull');
$end=1;
}else if($result=='expired'){
p('status = expired');
$end=1;//ex
}else{
d('status = Pending');
sleep(10);
}
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I dont know a good MVC pattern, now learn... So, I want to make: obtain rows from database, if result none (0 rows) print "we have no results", otherwise print results.
In model I have this php code
function getAutos () {
//here connect to database
$res = $this->db->query("SELECT names FROM auto");
if ($res->num_rows == 0) {
return "we have no results";
}
else {
return $res;
}
}
this function returns object or string, right? now in view I make:
<!--some html code -->
<?php
$resultFromGetAutos = /*result from function getAutos ()*/
if (is_object(resultFromGetAutos)) {
while ($row = resultFromGetAutos->fetch_assoc()) {
echo row['names']."<br>";
}
}
else {
echo resultFromGetAutos;
}
?>
<!--some html code -->
It works, but as I understood, many PHP code in view, is not right MVC, that is when I check result type in view: if (is_object(Resultat)) {do something} else { do other something } this is not right MVC conception? if not right, how is right way in such situations?
The model in MVC is not a class or object. Model is layer, which contains all domain business logic in the application. While it might interact with databases, it should not be directly creating the connection at any point. You might read this post. It will contain some directions.
The bottom line here is that, what you are calling "model", isn't even close to the original concept.
As for the views, in proper MVC (or MVC-inspired) pattern implementation the views are responsible for all of presentation logic. That would mean that views make the decisions about what will be visible to the user. It is determined by acquiring information from model layer (by directly requesting it in classical MVC and Model2 MVC, and acquiring it through controller-like structure in MVP and MMVM patterns).
In web applications the view creates a response. The form of response would differ based on the for of the request or interface that was used. View can either create response by combining multiple templates or just sen a HTTP location header.
One of the principles of MVC design is that the Model and the View don't directly access eachother, even don't know about eachother.
Mostly the View is the most stupid. It should not understand the data that it is displaying, just how it should display 'data', which could be everything.
You should have a controller that gets noticed by the view if it wants the autos. The controller should then ask the model for the autos, and parse the returned value of the model to a format the view can directly display.
Or, if you should have these autos already on page load, do it via the constructor (example).
It should look like this:
<View> // you shouldn't include that, that's just that readers notice it is the view.
<?php
// a bunch of other code
function AutoView($whatViewShouldDisplay) { // should be the constructor, OOP PHP is not my strongest point
$content = $whatViewShouldDisplay;
echo $content;
}
?>
<Controller>
<?php
// Bunch of other code
function AutoController() { // should-be constructor
$model = new AutoModel();
$result = $model->getAutos();
if ($result->num_rows != 0) {
while ($row = resultFromGetAutos->fetch_assoc()) {
$viewContent .= row['names']."<br>";
}
}
else {
$viewContent = "Sorry, no results found.";
}
$view = new AutoView($viewContent);
}
?>
<Model>
<?php
// Bunch of other code
function getAutos() {
return $this->db->query("SELECT names FROM auto");
}
?>
As you see, as long as the Model implements the method getAutos() that returns a SQL result set and the view has a one-args constructor you can replace them with everything!
Or, with your code in mind:
<!--some html code -->
<?php
$text = $controller->requestContentForThisPlace(); // Something like getMainContent()? I don't know where this is on your page.
echo $text;
?>
And the Controller for your code would implement this method:
function requestContentForThisPlace() {
$result = $model->getAutos();
if ($result->num_rows != 0) {
while ($row = resultFromGetAutos->fetch_assoc()) {
$content .= row['names']."<br>";
}
}
else {
$content = "Sorry, no results found.";
}
return $content;
}
I am quite new to programming, when I develop my program I use a simple strategy to debug it: I write the program to print along the debugging messages as it operate the significant statements, for example
function foo1($number)
{
//foo_print("I am function foo1({$number}). <br/>");
//foo_print("I am going to increase 'count' by {$number}. <br/>");
$GLOBALS["count"] = $GLOBALS["count'] + $number;
//foo_print("Now 'count' = {$GLOBALS["count"]}, I finished my task, BYE BYE. <br/>");
}
function isFoo($number)
{
//foo_print("I am function isFoo({$number}). <br/>");
//foo_print("I am checking if the number < 3 or not, if so, it is Foo, if not, it is not Foo. <br/>");
if($number <= 3)
{
//foo_print("Found that number = {$number} <= 3, I return true, BYE BYE. <br/>");
return true;
}
//foo_print("Found that number = {$number} > 3, I return false, BYE BYE. <br/>");
return false;
}
I call them debugging messages but, as you see, they're actually the thoroughly comments describing what does the program do on each line. I just write the function foo_print() to print them out when I am debugging the program. And comment them out in real use.
Instead of inserting and removing the comment sign '//' line by line in and out when switch between real run mode and debugging mode, I have the function foo_print to do the work: It can be set to turn on or off.
define(FOO_PRINT, 1)
function foo_print($message)
{
if(FOO_PRINT) print $message;
// if FOO_PRINT == 0 then do nothing.
}
But I think this method is ineffective, it has to check FOO_PRINT every time before printing a message.
My question is either or both of the following
Can I do something to tell php to ignore my foo_print() function when I don't want to use it?
Perhaps, instead of using foo_print function, I should write the messages in plain comment style using '//' sign and then tell php interpreter to print those comment messages when in debugging mode. Can I do that?
I think, other than debugging ease, this method will be of advantage that it can help me understand the program when I come back to see it in later days. (It very long and complicated for me that I believe I will forget it soon.)
I found it very complicated for me now to use advanced IDEs and debugging tools to develop my program. I believe some of these advanced debugging tools can do something similar to what I want, but I've tried on PHP-eclipse and xdebug for a week and it got me nowhere. thank you very much.
You could define two functions, one of which outputs the debug data and the other one doesn't. Then use a variable name to contain the name of the function you want to call and do your debugging by calling the function in the variable. Like this:
function debug_print($data) {
echo $data;
}
function debug_none($data) {
}
$debug = 'debug_print';
$debug('Testing one'); // This prints out 'Testing one'
$debug = 'debug_none';
$debug('Testing two'); // This doesn't print out anything
If you do this, don't forget to add global $debug to any functions that want to use the function.
EDIT: There is also a more object oriented way to achieve the same result. You could define an interface and write a couple of implementations for it, allowing you to choose which one to use at runtime.
$debugmode = true;
interface Debugger {
public function out($data);
}
class EchoDebugger implements Debugger {
public function out($data) {
echo $data;
}
}
class NullDebugger implements Debugger {
public function out($data) {
// Do nothing
}
}
if($debugmode)
$debugger = new EchoDebugger();
else
$debugger = new NullDebugger();
$debugger->out('This will be output if $debugmode is true');
No bud,
there is no such thing possible, and you have to define a condition every time.
This cannot be done in code of php