导入软件包或自动加载PHP? [英] Import package or autoloading for PHP?

查看:72
本文介绍了导入软件包或自动加载PHP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于将文件包含在PHP项目中,您建议使用哪种解决方案?

What solution would you recommend for including files in a PHP project?

  1. 没有手动调用require/include函数-一切都通过自动加载功能加载
  2. 在需要时导入包.

这是软件包导入API:

Here is the package importing API:

import('util.html.HTMLParser');
import('template.arras.*'); 

在此函数声明中,您可以使用点使字符串爆炸(包层次结构定界符),循环浏览特定包(文件夹)中的文件以仅包含其中一个文件,也可以包含所有文件(如果在文件末尾找到星号)字符串,例如("template.arras.*").

In this function declaration you can explode the string with dots (package hierarchy delimeter), looping through files in particular package (folder) to include just one of them or all of them if the asterisk symbol is found at the end of the string, e.g. ('template.arras.*').

我可以在包导入方法中看到的好处之一是,它可以迫使您使用更好的对象分解和类分组.

One of the benefits I can see in package importing method, is that it can force you to use better object decomposition and class grouping.

我可以在自动加载方法中看到的缺点之一-自动加载功能可能会变得很大,而且不是很明显/可读性很强.

One of the drawbacks I can see in autoload method - is that autoload function can become very big and not very obvious/readable.

您怎么看?

  • 您可以在每种方法中列举哪些优点/缺点?
  • 如何找到该项目的最佳解决方案?
  • 如何知道如果使用软件包管理,是否会出现性能问题?

推荐答案

我广泛使用__autoload().我们在应用程序中使用的autload函数为旧类的向后兼容性进行了一些调整,但是在创建允许autoload()相当正常工作的新类时,我们通常遵循约定:

I use __autoload() extensively. The autload function that we use in our application has a few tweaks for backwards compatibility of older classes, but we generally follow a convention when creating new classes that allow the autoload() to work fairly seemlessly:

  • 一致的类命名:每个类在其自己的文件中,每个类都以驼峰式命名,并用下划线分隔.这映射到类路径.例如,Some_CoolClass映射到我们的类目录,然后映射到'Some/CoolClass.class.php'.我认为某些框架使用此约定.
  • 明确需要外部类:由于我们无法控制所使用的任何外部库的命名,因此我们使用PHP的require_once()函数加载它们.
  • Consistent Class Naming: each class in its own file, each class is named with camel-case separated by an underscore. This maps to the class path. For example, Some_CoolClass maps to our class directory then 'Some/CoolClass.class.php'. I think some frameworks use this convention.
  • Explicitly Require External Classes: since we don't have control over the naming of any external libraries that we use, we load them using PHP's require_once() function.

这篇关于导入软件包或自动加载PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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