Z-PHP_v5

Z-PHP5 文档


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

<h1>框架的自动加载机制</h1> <p><strong>根据事先定义的 命名空间 =&gt; 目录路径 的映射关系来加载所需文件</strong> <strong>&lt;font color=red&gt;如果&lt;/font&gt;使用第三方的SDK包当中有自动加载的 spl_autoload_register() 函数,会造成&lt;font color=red&gt;冲突&lt;/font&gt;。</strong> <strong>&lt;font color=red&gt;解决方法&lt;/font&gt;是使用 Zautoload() 函数替换SDK包内的 spl_autoload_register() 函数</strong> <strong>函数体的内容不变,也就是说只是换了一下函数名,原来该怎么用还是怎么用</strong></p> <h1>框架默认的命名空间路径</h1> <pre><code>'app'=&amp;gt; P_APP, // 应用目录 'sdk' =&amp;gt; P_ROOT . 'sdk/', // 根目录下的sdk目录 'lib' =&amp;gt; P_ROOT . 'lib/', // 根目录下的lib目录 'model' =&amp;gt; P_ROOT . 'model/', // 根目录下的model目录 'nec' =&amp;gt; P_ROOT . 'nec/', // 根目录下的nec目录</code></pre> <h1>自定义命名空间映射</h1> <p><strong>将 mapping.php 文件放置在&lt;font color=red&gt;根目录&lt;/font&gt;下的config或者是&lt;font color=red&gt;应用目录&lt;/font&gt;下的config</strong> <strong>文件内可使用框架内部的&lt;font color=red&gt;路径常量&lt;/font&gt;,路径必须以 &lt;font color=red&gt;/ 结尾&lt;/font&gt;</strong> <strong>mapping.php 文件格式如下</strong></p> <pre><code>&amp;lt;?php return[ 'base_ctrl' =&amp;gt; P_ROOT . 'base/ctrl/', // 将 base_ctrl 映射到 /base/ctrl 目录 'base_model' =&amp;gt; P_ROOT . '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>&amp;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>&amp;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>&amp;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>&amp;lt;?php namespace app\ctrl; class index{ function index(){ \common\sub\abc::action(); $abc = new \common\sub\abc(); } }</code></pre></li> </ul>

页面列表

ITEM_HTML