我想知道在函数中包含()库文件是否被认为是不好的做法?
我的网站的一部分使用了 Sphinx 搜索引擎,但通过将 sphinxapi.php 包含在我的主站点范围的“配置”文件中来将其添加到每个页面似乎效率很低。
相反,我做了以下事情:
class sphinxSearch
{
/*
* Performs a standard listing search
*/
function listings($filter, $sdb)
{
// include the sphinx api
require_once SITE_INCLUDE_PATH.SEP.'Sphinx/sphinxapi.php';
// set default options
$search = new SphinxClient();
$search->SetServer(SPX_HOST, SPX_PORT);
$search->SetConnectTimeout(1);
$search->SetArrayResult(false);
// blah blah blah
return $result;
}
/*
* Listing autocomplete box
*/
function autoComplete ($query, $sdb)
{
require_once SITE_INCLUDE_PATH.SEP.'Sphinx/sphinxapi.php';
// set default options
$search = new SphinxClient();
$search->SetServer(SPX_HOST, SPX_PORT);
$search->SetConnectTimeout(1);
$search->SetArrayResult(false);
// blah blah blah
}
}
或者我缺少更好的方法吗?
提前致谢。
最佳答案
我认为这种方法本质上没有任何错误。
为了提高性能,可以做的一件事是对在 sphinxapi.php
中实现的类进行 class_exists
调用,并使用 require 而不是这样做require_once,如果您在单页重新加载时多次调用这些函数,则尤其如此。请参阅Understanding class required and exist
例如:
if (!class_exists('SphinxClass')) require "sphinx/shinxapi.php";
然后更快
require_once "sphinx/shinxapi.php";
到目前为止,最好的选择是设置自动加载器,这样您就不必担心包含任何文件。看看http://phpmaster.com/autoloading-and-the-psr-0-standard/ ,它将解释该过程。
关于php - 包含内部函数被认为是不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16723819/