PSR-0 : PHP autol…

本文详细阐述了构建符合规范的命名空间与类结构的方法,包括顶级命名空间设置、子命名空间的使用、下划线字符的处理、文件扩展名规定以及加载机制的兼容性。通过具体示例展示了如何正确实现上述规范,帮助开发者构建清晰、易于维护的代码库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

强制约定

  • 一个合格的名空间-类应当遵循这样的结构 \\(\)*
    A fully-qualified namespace and class must have the following structure \\(\)*
  • 每个名空间需要有一个顶级名空间 (“Vendor Name”)(提供者名称).
    Each namespace must have a top-level namespace (“Vendor Name”).
  • 每个名空间可以有任意多个子名空间
    Each namespace can have as many sub-namespaces as it wishes.
  • 从文件系统载入时,每个名空间分隔符将被转换为一个路径分隔符
    Each namespace separator is converted to a DIRECTORY_SEPARATOR when loading from the file system.
  • 类名中的每个下划线符( _ )将被转化为一个路径分隔符,名空间中的下划线符( _ )没有任何特定含义
    Each character in the CLASS NAME is converted to a DIRECTORY_SEPARATOR. The character has no special meaning in the namespace.
  • 一个合格的名空间-类所对应加载的文件必须是以.php结尾的
    The fully-qualified namespace and class is suffixed with .php when loading from the file system.
  • Vendor Name(提供者名称)、名空间、类名中的字符可以是大小写的任意组合
    Alphabetic characters in vendor names, namespaces, and class names may be of any combination of lower case and upper case.

范例

  • \Doctrine\Common\IsolatedClassLoader => /path/to/project/lib/vendor/Doctrine/Common/IsolatedClassLoader.php
  • \Symfony\Core\Request => /path/to/project/lib/vendor/Symfony/Core/Request.php
  • \Zend\Acl => /path/to/project/lib/vendor/Zend/Acl.php
  • \Zend\Mail\Message => /path/to/project/lib/vendor/Zend/Mail/Message.php

名空间与类名中的下划线

  • \namespace\package\Class_Name => /path/to/project/lib/vendor/namespace/package/Class/Name.php
  • \namespace\package_name\Class_Name => /path/to/project/lib/vendor/namespace/package_name/Class/Name.php

我们指定的标准应当成为保证autoload机制互通性的最小化规范。
你可以利用这个示例SplClassLoader加载PHP5.3的类来测试自己是否遵循了本规范

The standards we set here should be the lowest common denominator for painless autoloader interoperability. You can test that you are following these standards by utilizing this sample SplClassLoader implementation which is able to load PHP 5.3 classes.

实例实现

以下是一个实现上述规范的autoload函数简单示例
Below is an example function to simply demonstrate how the above proposed standards are autoloaded.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值