开发者

Is switch/case okay to use with long scripts?

I was wondering if the following is okay:

So I have a bunch of different types of records I want to add and the forms for each type is different. For example, Apple.php, Banana.php, Chocolate.php. I don't want to create a different processing php file for each one and would like to have all 开发者_Go百科the processing instructions on one file, add.php, instead of having addApple.php, addBanana.php, etc.

Is it okay to find the url and use a switch/case to run the instructions based on the url?

for example:

$uri = $_SERVER['HTTP_REFERER'];
switch (true) {
case (strstr($uri,'apple')):
  //20 lines of code to insert records
break;
case (strstr($uri,'banana')):
 //30 lines of code to insert records
break;

I am wondering because in a lot of the switch/case examples, it seems like it's often used to echo something.


Long portions of code in each case will work, technically speaking ; but it'll lead to code that's hard to read/maintain.

I suppose an alternative could be to replace your 20-30 lines of code by function-calls ; this way :

  • You'd have a switch/cases structure that is still readable : not too long,
  • And you'd have a function for each case.


Use parameter in $_GET and use it together with switch() statement It is better than lookup how the URL looks like and make decision. That would be the case only if you can use mod_rewrite to call urls like this: /add/banana,/add/chocolate

so it's better to do it like this:

call: add.php?type=banana

php:

$param = $_GET['type'];
switch($param){
case.....
}

and about that you have a long code to work with, you should make some function which will work with datas abstractly like

function add_type($type = "defaulttype", $data = null){
    // do with data whatever you want, like creating save-arrays and querying db layer
}


It will work, but I think it's better to use separate functions to save the records

$uri = $_SERVER['HTTP_REFERER'];
switch (true) {
  case (strstr($uri,'apple')):
    saveApple();
    break;
  case (strstr($uri,'banana')):
    saveBanana();
    break;
}

This keeps your switch statement a lot shorter (and more readable). Also the different functions add to readability and maintainability.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜