优化这段 PHP 代码?

发布于 2024-12-03 01:57:26 字数 316 浏览 3 评论 0 原文

我目前正在开发一个包含许多数据源的混搭。为了在一页上显示用户想要的所有提要,我当前正在使用 if 语句与 MySQL 数据库进行交叉检查,如下所示:

if($var["type"]=="weather") 

$var 是调用 < code>mysqli_fetch_array

然后包括与下面的功能(例如天气)相关的代码,然后是另一个提要的另一个“if”语句,依此类推。问题是会有很多提要,并且拥有所有这些“if”语句将是缓慢且多余的。

有什么办法可以优化这个 PHP 代码吗?

I am currently working on a mashup that incorporates many data feeds. In order to display ALL of the feeds that the user wants on one page, I am currently using if statements to cross-check with the MySQL database like this:

if($var["type"]=="weather") 

$var being the result of a call to mysqli_fetch_array

and then including code relevant to the function (e.g. weather) underneath, and then another "if" statement for another feed, so on so on. The problem is that there will be many feeds, and having all these "if" statements will be slow and redundant.

Is there any way to optimize this PHP code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

滿滿的愛 2024-12-10 01:57:26

另一种解决方案可能是使用关联数组将“类型”映射到自定义函数。

例如(伪代码)

function handle_wheater_logic() {
   // ... your code goes here
}

function handle_news_logic() {
  // .. your code goes here
}


$customFunctions = array("wheater" => "handle_wheater_logic", "news" => "handle_news_logic");

while ($row = mysql_fetch_...) {
    call_user_func ($customFunctions[$row["type"]])
}

这将消除使用大量 if 语句的需要。您也可以在配置文件中进行“类型到函数”映射,或者只存储自定义函数的名称以调用数据库表中的每个“类型” - 这取决于您。

当然,您也可以将参数传递给自定义函数。只需查看 call_user_func[_array] 的文档即可。

Another solution might be to map the "type" to a custom function using associative arrays.

e.g. (pseudo code)

function handle_wheater_logic() {
   // ... your code goes here
}

function handle_news_logic() {
  // .. your code goes here
}


$customFunctions = array("wheater" => "handle_wheater_logic", "news" => "handle_news_logic");

while ($row = mysql_fetch_...) {
    call_user_func ($customFunctions[$row["type"]])
}

This would eliminate the need to use a lot of if statements. You might as well do the "type to function" mapping in a configuration file or maybe just store the name of the custom function to call for each "type" in a database table - that's up to you.

You can, of course also pass parameters to custom function. Just checkout the documentation for call_user_func[_array].

遗弃M 2024-12-10 01:57:26

试试这个:

$methods = array(
    "weather" => function() {
        // code
    },

    "otheroption" => function() {
    }
);

只需使用 $var["type"] 作为数组中的索引来获取函数:

$methods[$var["type"]]();

显然,为了更好的可读性,您可以做类似的事情:

$methods = array(
    "weather" => "wheater_function",

    "otheroption" => "other_function"
);

然后以这种方式调用函数:

call_user_func($methods[$var["type"]]);

为了更加面向对象,我们显然可以在数组中存储实现特定接口的对象,或者存储重新定义 __call() 魔术方法的对象并像函数一样使用它。

Try this:

$methods = array(
    "weather" => function() {
        // code
    },

    "otheroption" => function() {
    }
);

Just use then $var["type"] as a index in the array to get the function:

$methods[$var["type"]]();

You can obviuosly, for better readbility do something similar:

$methods = array(
    "weather" => "wheater_function",

    "otheroption" => "other_function"
);

and then call the functions this way:

call_user_func($methods[$var["type"]]);

To be even more object oriented we can obviously store in the array objects implementing a particular interface, or store object redifining the __call() magic method and use it like functions.

中二柚 2024-12-10 01:57:26

您可以使用 switch 语句。

You can use a switch statement.

梓梦 2024-12-10 01:57:26

消除大量 if 语句和仅检查一个条件的大量 switch 语句的一个好解决方案是实现一种设计模式,例如策略模式。

这样您就可以将每种类型的代码分开,从而更容易概览和管理。

这是实现的示例 http://blogs.microsoft.co.il/blogs/gilf/archive/2009/11/22/applying-strategy-pattern-instead-of-using-switch-statements.aspx

即使您不会严格执行此操作,它也会为您提供一些关于如何优雅地解决此问题的想法。

A good solution for eliminating a lot of if statements and a huge switch statement just checking for one condition, would be to implement a design pattern such as the Strategy pattern.

This way you will have the code for each type separated, which makes it easier to overview and manage.

Here's an example of an implementation http://blogs.microsoft.co.il/blogs/gilf/archive/2009/11/22/applying-strategy-pattern-instead-of-using-switch-statements.aspx

Even if you won't implement this strictly it will give you some ideas on how to solve this elegantly.

谜兔 2024-12-10 01:57:26

创建一个将函数与每种提要类型关联起来的数组:

$actions = array("weather" => "getWeather",
                 "news"    => "getNews");

然后使用 call_user_func 调用正确的函数:

call_user_func($actions[$var["type"]]);

Create an array that associates a function to each feed type:

$actions = array("weather" => "getWeather",
                 "news"    => "getNews");

Then use call_user_func to call the correct one:

call_user_func($actions[$var["type"]]);
痴梦一场 2024-12-10 01:57:26

多态性的救援。

inteface FeedInterface {
  public function retrieve($params);
}

class FeedWeather implements FeedInterface {

  public function retrieve($params) {
    //retrieve logic for weather feed
  }

}

class FeedSports implements FeedInterface {

  public function retrieve($params) {
    //retrieve logic for sports feed
  }

}

通过使用 PHP 类自动加载,上述每个声明都可以位于单独的文件中,也可能具有命名空间。那么您的提要检索代码可能如下所示:

$class = 'Feed'.$var["type"];
$feed = new $class;

$feed->retrieve($params);

这过于简化,并且需要一些额外的代码来进行错误处理、发现不存在的类等,但这个想法应该很清晰。

Polymorphysm for the rescue.

inteface FeedInterface {
  public function retrieve($params);
}

class FeedWeather implements FeedInterface {

  public function retrieve($params) {
    //retrieve logic for weather feed
  }

}

class FeedSports implements FeedInterface {

  public function retrieve($params) {
    //retrieve logic for sports feed
  }

}

With use of PHP class autoloading, each of above declarations can be in a separate file, possibly namespaced as well. Then your feed retrieval code could look like this:

$class = 'Feed'.$var["type"];
$feed = new $class;

$feed->retrieve($params);

That's overly simplified and would need some additional code for error handling, discovery of non-existing classes and such, but the idea should be clear.

星星的軌跡 2024-12-10 01:57:26

使用 If 语句或 Switch 语句将比您关心的更快。它可能看起来很难看并且维护起来很麻烦,但它很快。

Using either an If Statement or a Switch statement will be faster than you care about. It might look ugly and be cumbersome to maintain but it will be fast.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文