在需要时自动加载功能/类库 [英] Auto-load function / class libraries when needed

查看:121
本文介绍了在需要时自动加载功能/类库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,有一点背景。我工作的公司使用一个大量的函数/类库,它被包含在每一页上。成千上万的函数,其中90%可能甚至不会在页面上调用。



为了减轻服务器负载,我我一直在试验更聪明的图书馆设置。为此,我已将整个文件分割成分类库文件(即sql.functions.php,date.functions.php等)。

不幸的是,包括每个页面上的每个文件都根本没有帮助,并且有选择地包含文件几乎是不可能的,并且很容易出错。



我在寻找的是设置类似于PHP的 ___ autoload()函数,它会自动搜索专门命名的文件,以防未知类启动,试图找到它。

 <?php 
function ___ autoload($ class_name){
require_once($ class_name。'。class.php');
}
?>

然而,这个函数不适用于函数调用,仅适用于类。



有没有一种方法可以在调用未定义的函数(例如 html_insert_button(); )时自动寻找并包含一个named函数库?

(在上面的例子中, html_functions.php 需要加载,因为它共享函数的前缀)

解决方案

我不相信有一种方法可以自动加载功能。有些人在 SitePoint论坛上争论。



我认为这将是一个非常棒的加法,因为它可以让你减少输入数量。

我采用这种方法来加载我的函数,与CodeIgniter非常相似:



每当我去使用一组函数时,我会调用一个库(html)函数,它将包含我将要使用的库(确保它只包含一次)。

 
函数库($名称)
{
include($ name。。lib.php);
}

可能不是您正在寻找的答案,但这就是我的做法。


First, a little background. The company I work for uses a massive function / class library, which gets included on every single page. Thousands and thousands of lines of functions, 90% of which probably won't even be called on a page.

In an attempt to lighten the server load a little, I've been experimenting with smarter library setups. To this end, I've split the entire file into categorized library files (i.e. sql.functions.php, date.functions.php, and others.)

Unfortunately, including every single file on every page doesn't help at all, and selectively including files is nearly impossible and very error-prone.

What I'm looking for is a setup similar to PHP's ___autoload() function, which automatically searches for specifically named files in case an unknown Class is initiated, in an attempt to find it.

<?php
  function ___autoload($class_name) {
    require_once($class_name.'.class.php');
  }
?>

However, this function does not work on function calls, only classes.

Is there a way to instruct PHP, when calling an undefined function (i.e. html_insert_button();), to automatically look for and include a named function library?

(In the above case, html_functions.php would need to be loaded, since it shares the function's prefix)

解决方案

I don't believe there is a way to autoload functions unfortunately. Some guys argued about this on the SitePoint forums.

I for one think it would be an awesome addition because it would let you reduce the amount of inlcudes.

I took this approach to loading my functions, very similar to CodeIgniter's:

Whenever I go to use a set of functions, I will call a library("html") function, that will include the library that I am about to use (making sure that it only includes it once).

function library($name)
{
    include($name .".lib.php");
}

Probably not the answer you are looking for, but that is how I do it.

这篇关于在需要时自动加载功能/类库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆