如何面向命名空间开发

框架原生在不同PHP版本下支持不同的特性

of_xx 类可以按照命名空间方式调用

  1. 假如现在有个框架类 of_base_com_str
  2. 当在一个 php < 5.3 的网络环境下, 只能通过 of_base_com_str 方式调用
  3. 当在一个 php >= 5.3 的网络环境下, 还可以通过 \of\base\com\str 方式调用
  4. 当然也支持命名空间下的其它特性, 比如 use 的使用

命名空间模式的寻类规则

  1. 非命名空间模式下, 通过"_"对类名分割确定路径, 如: 类 demo_test 一定在 系统根目录\demo\test.php 中
  2. 同样的命名空间模式下, 通过"\"对类名分割确定路径, 如: 类 demo\test 也一定在 系统根目录\demo\test.php 中
  3. 自然 test.php 的写法也要是标准的, namespace demo; class test {}

框架支持命名空间方式的回调

  1. 框架内部统一回调方法 of::callFunc 支持包括命名空间在内的不同格式的调用, 如 "demo\test::action" 或 [demo\test, action]
  2. 那么对应的工具封装也是支持同样方式的, 如 分页列表中的 call 参数

关于命名空间的使用演示

创建入口 /index.php

<?php
//加载框架唯一入口
require dirname(__FILE__) . '/include/of/of.php';

//调度代码, 这里的"c"参数假设是 "demo_test", "a"参数为 "index"
if (isset($_GET['c'])) {
    //将 demo_test 转化成 demo\test 方式
    $_GET['c'] = strtr($_GET['c'], '_', '\\');
    //直接调用 demo\test 实例中的 index 方法
    $result = of::dispatch($_GET['c'], isset($_GET['a']) ? $_GET['a'] : 'index',  true);
    //返回数组转成json
    if (is_array($result)) echo json_encode($result);
}

创建控制层 /demo/test.php

<?php
namespace demo;
use of\base\com;

//注意在命名空间下使用框架要加"\"
class test extends \L {
    /**
     * 描述 : 通过index.php?c=demo_test访问
     */
    function index() {
        //调用 \of\base\com\str::rc4(1, 2) 加密方法
        var_dump(com\str::rc4(1, 2));
        //调用 (new \of\base\com\str)->rc4(1, 2) 加密方法
        var_dump($this->_str->rc4(1, 2));
    }
}
//安全校验
return true;