我使用下面的类在我的Web应用程序上路由所有php请求。我能改进吗?
/*route*/
class route
{
function __construct($a)
{
if(isset($_FILES['ufile']['tmp_name'])) // handles file uploads
{
new upload();
}
elseif(isset($_POST['a'])) // handles AJAX
{
$b=$_POST['a'];
switch($b)
{
case '0':
new signin();
break;
case '1':
new signup();
break;
case '2':
session::finish();
break;
case '3':
new bookmark('insert');
break;
case '3a':
new bookmark('delete');
break;
case '4':
new tweet();
break;
default:
echo "ajax route not found";
break;
}
}
elseif($a!=0) // handles views
{
new view($a);
}
else
{
// route not found
}
}
}
验证(通过)
/*ROUTE
// Test Code - create entry
new route(0);
new route(1);
$_FILES['ufile']['tmp_name']='test file';
new route(0);
unset($_FILES['ufile']['tmp_name']);
$_POST['a']=0;
new route(0);
// Test Cases
// Case 0: echo "not routed: <br>";
// Case 1: echo "view created: $a <br>";
// Case 2: echo "file uploaded <br>";
// Case 3: echo "ajax responded: <br>";
*/
答案 0 :(得分:1)
public static function route($a)
{
// The first if statement is redundant this line will accomplish the
// same as the if/else because if post[a] is not set it will become null
$b=$_POST["a"];
// now that b is a, it's really one switch statement
if( $b==0 && $a==0 )
switch( $b )
{
case '0':
new signin();
break;
case '1':
new signup();
general::upload();
break;
case '2':
session::finish();
break;
case '3':
new bookmark('insert');
break;
case '3a':
new bookmark('delete');
break;
case '4':
new tweet();
break;
default:
view::posts_all();
break
}
}elseif( $a==1 )
view::bookmarks();
else
view::posts_all();
放手一搏,祝你好运。 (旁注:数字情况下的引号是可选的,3a不是。我把它们放在那里因为它们是原始的。你可以通过完全摆脱$ b并在$上运行开关来进一步减少它_POST ['a'])
答案 1 :(得分:0)
if / else语句允许您设置特定条件评估,而switch / case只允许您设置变量可能采用的某些特定值(即在开关/情况下,您不能说$b > 10
之类的内容)。
除此之外,if / else或switch / case之间没有太大区别。
我建议您使用switch / case构造,因为您只是将$b
与一组常量进行比较。
此外,请记住过早优化是万恶之源:)