加载中...

2.6 添加自动加载文件 init_autoloader.php


路径:/application/init_autoloader.php

if (defined('LIB')) {
        include LIB . '/Zend/Loader/AutoloaderFactory.php';
        Zend\Loader\AutoloaderFactory::factory(array(
            'Zend\Loader\StandardAutoloader' => array(
                'autoregister_zf' => true
            )
        ));
}

if (!class_exists('Zend\Loader\AutoloaderFactory')) {
    throw new RuntimeException('Unable to load ZF2. ');
}

代码解释:

  • if (defined('LIB')) 判断是否有定义预定义变量指向ZF2类库
  • include LIB . '/Zend/Loader/AutoloaderFactory.php' 导入ZF2框架自动加载工厂文件
  • Zend\Loader\AutoloaderFactory::factory(array()) 对自动加载工厂类进行设置
  • if (!class_exists('Zend\Loader\AutoloaderFactory')) 判断工厂类是存在,如果不存在则抛出异常

下面是 init_autoloader.php 的另一个写法,此写法其实是 Zend studio 或 netbeans 创建项目时自动生成的写,这样的写法其实是加入对 phpunit 单元测试的支持。phpunit 的测试环境一般都是在命令行上操作完成,所以这样的写法也是对命令行环境的一种设置,在此就不多加详解;下面只贴出代码。

if (file_exists('vendor/autoload.php')) {
    $loader = include 'vendor/autoload.php';
}

if (defined('LIB')) {
    if (isset($loader)) {
        $loader->add('Zend', LIB);
    } else {
        include LIB. '/Zend/Loader/AutoloaderFactory.php';
        Zend\Loader\AutoloaderFactory::factory(array(
            'Zend\Loader\StandardAutoloader' => array(
                'autoregister_zf' => true
            )
        ));
    }
}

if (!class_exists('Zend\Loader\AutoloaderFactory')) {
    throw new RuntimeException('Unable to load ZF2.');
}

还没有评论.