Z-PHP_v4


关于自动加载和命名空间的映射

<h1>框架的自动加载机制</h1> <p><strong>根据事先定义的 命名空间 =&gt; 目录路径 的映射关系来加载所需文件</strong> <strong><font color=red>如果</font>使用第三方的SDK包当中有自动加载的 spl_autoload_register() 函数,会造成<font color=red>冲突</font>。</strong> <strong><font color=red>解决方法</font>是使用 Zautoload() 函数替换SDK包内的 spl_autoload_register() 函数</strong> <strong>函数体的内容不变,也就是说只是换了一下函数名,原来该怎么用还是怎么用</strong></p> <h1>框架默认的命名空间路径</h1> <pre><code>'z'=&gt; P_CORE . 'z/', // core下的z目录 'ext' =&gt; P_CORE . 'ext/', // core下的ext目录 'root' =&gt; P_ROOT, // 根目录 'common' =&gt; P_COMMON, // common目录 'libs' =&gt; P_ROOT . 'libs/', // libs目录 'app' =&gt; P_APP, // 当前的应用目录 'module' =&gt; P_MODULE, // 当前的模块目录 'ctrl' =&gt; , // 当前的控制器目录 'model' =&gt; , // 当前应用或模块下的model目录 'lib' =&gt; , // 当前应用或模块下的lib目录 'base' =&gt; , // 当前应用或模块下的base目录</code></pre> <h1>自定义命名空间映射</h1> <p><strong>将 mapping.php 文件放置在<font color=red>根目录</font>下的common或者是<font color=red>应用目录</font>下的common</strong> <strong>文件内可使用框架内部的<font color=red>路径常量</font>,路径必须以 <font color=red>/ 结尾</font></strong> <strong>mapping.php 文件格式如下</strong></p> <pre><code>&lt;?php return[ 'base_ctrl' =&gt; P_BASE . 'ctrl/', // 将 base_ctrl 映射到 当前应用版本或模块/base/ctrl 目录 'base_model' =&gt; P_BASE . 'model/', // 将 base_model 映射到 当前应用版本或模块/base/model 目录 ];</code></pre> <h2>可能有人搞不太明白命名空间和路径的关系,下面解释一下:</h2> <p><strong>例如 命名空间 common 被映射到了 /common 目录</strong></p> <ul> <li> <p><strong>在common目录下的类文件的命名空间就是common,该目录下的类文件开头就要写 namespace common;</strong></p> <pre><code>&lt;?php namespace common; class abc{ function action(){ } }</code></pre> </li> <li> <p><strong>如果类文件不是在common的根目录下,而是在 /common/sub 目录下,那么命名空间就是 common\sub,该目录下的类文件开头就要写 namespace common\sub;</strong></p> <pre><code>&lt;?php namespace common\sub; class abc{ function action(){ } }</code></pre> </li> </ul> <p><strong>使用这些类文件的时候就直接加上命名空间使用就可以了,不需要require或是include</strong> <strong>例如类文件:common/sub/abc.class.php</strong></p> <ul> <li> <p><strong>在文件开头声明一下是common\sub 命名空间下的abc类:use common\sub\abc;</strong></p> <pre><code>&lt;?php namespace ctrl; use common\sub\abc; class index{ function index(){ abc::action(); $abc = new abc(); } }</code></pre> </li> <li><strong>如果没有显示声明,使用的时候就需要补全命名空间:</strong> <pre><code>&lt;?php namespace ctrl; class index{ function index(){ \common\sub\abc::action(); $abc = new \common\sub\abc(); } }</code></pre></li> </ul>

页面列表

ITEM_HTML