Zend Framework教程之Application用法实例详解


Posted in PHP onMarch 14, 2016

本文实例讲述了Zend Framework教程之Application用法。分享给大家供大家参考,具体如下:

Zend_Application是Zend Framework的核心组件。Zend_Application为Zend Framework应用程序提供基本功能,是程序的入口点。它的主要功能有两个:装载配置PHP环境(包括自动加载),并引导应用程序。

通常情况下,通过配置选项配置Zend_Application构造器,但也可以完全使用自定义方法配置。以下是两个使用用例。

Zend_Application配置选项

构造函数:

/**
 * Constructor
 *
 * Initialize application. Potentially initializes include_paths, PHP
 * settings, and bootstrap class.
 *
 * @param string          $environment
 * @param string|array|Zend_Config $options String path to configuration file, or array/Zend_Config of configuration options
 * @throws Zend_Application_Exception When invalid options are provided
 * @return void
 */
public function __construct($environment, $options = null)
{
  $this->_environment = (string) $environment;
  require_once 'Zend/Loader/Autoloader.php';
  $this->_autoloader = Zend_Loader_Autoloader::getInstance();
  if (null !== $options) {
    if (is_string($options)) {
      $options = $this->_loadConfig($options);
    } elseif ($options instanceof Zend_Config) {
      $options = $options->toArray();
    } elseif (!is_array($options)) {
      throw new Zend_Application_Exception('Invalid options provided; must be location of config file, a config object, or an array');
    }
    $this->setOptions($options);
  }
}

Zend_Application配置方法

1.使用配置文件
2.使用配置数组

常见配置选项

Option Description
phpSettings 用于配置php.ini选项,要求是数组,数组的键应该是选项的的key.
includePaths 把附加的路径加入到include_path,要求是数组
autoloaderNamespaces 给Zend_Loader_Autoloader注册附加命名空间,为数组
bootstrap 可以是设置bootstrap引导类的路径的字符串,也可以是数组,数组元素要求为 'path' 和 'class'

注意:

选项名称不区分大小写。

Zend_Application的方法

Method Return Value Parameters Description
__construct( $environment,  $options = null) Void $environment: 必填。 表示当前应用环境的String。 典型的字符串可能包括 "development", "testing", "qa", or "production",他们必须已经被定义。 对应于配置文件文件中相关章节。 $options: 可选的,参数类型可能是: String :  指定Zend_Config 文件的配置路径. $environment 用于指定配置文件的哪一个章节 从1.10开始,可以设置多个配置文件路径,然后会被合并成一个单一的配置文件。 这样更灵活,便于重用。 在这种情况下的key是"config",其值是文件路径数组。 注:可以是路径字符串,或 array("config"=>array("/path1","/path2"[,...]));. Array : 配置应用的关联数组 Zend_Config:配置对象的实例 构造函数。 用于初始化配置对象。   实例化Zend_Loader_Autoloader。 通过传递给构造函数选项然后传递给setOptions()方法。
getEnvironment() String N/A 获取环境配置
getAutoloader() Zend_Loader_Autoloader N/A 获取Zend_Loader_Autoloader实例
setOptions(array $options) Zend_Application $options: 必填,要求是数组 所有选项都存储在引用内部,并多次调用该方法来合并选项。 会根据选项生产对于的setter方法。  例如,选项“phpSettings”对应setPhpSettings()。  (选项名称不区分大小写。)
getOptions() Array N/A
hasOption($key) Boolean $key: 判断是发有指定的配置 key不区分大小写。
getOption($key) Mixed $key: 获取指定的配置选项的值 key不区分大小写。如果不存在返回 NULL
setPhpSettings(array $settings, $prefix = '') Zend_Application $settings: 比填.PHP INI 的配置关联数组. $prefix: 可选. 为选项添加前缀
setAutoloaderNamespaces(array $namespaces) Zend_Application $namespaces: 必填.  传递命名空间字符串数组,通过Zend_Loader_Autoloader实例注册
setBootstrap($path, $class = null) Zend_Application $path: 必填.  可能是Zend_Application_Bootstrap_Bootstrapper实例, 自举类路径字符串,  格式为classname => filename的关联数组, 或key为“class”和value为“path”的关联数组。 $class: 可选. 如果 $path 是字符串, $class 类名称
getBootstrap() NULL |Zend_Application_Bootstrap_Bootstrapper N/A 获取注册的bootstrap实例.
bootstrap() Void N/A 调用 bootstrap的bootstrap() 引导应用.
run() Void N/A 调用bootstrap的 run()运行应用

配置举例:

默认:

// Create application, bootstrap, and run
$application = new Zend_Application(
  APPLICATION_ENV,
  APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap()
      ->run();

源代码

<?php
class Zend_Application
{  /**
   * Constructor
   *
   * Initialize application. Potentially initializes include_paths, PHP
   * settings, and bootstrap class.
   *
   * @param string          $environment
   * @param string|array|Zend_Config $options String path to configuration file, or array/Zend_Config of configuration options
   * @throws Zend_Application_Exception When invalid options are provided
   * @return void
   */
  public function __construct($environment, $options = null)
  {
    $this->_environment = (string) $environment;
    require_once 'Zend/Loader/Autoloader.php';
    $this->_autoloader = Zend_Loader_Autoloader::getInstance();
    if (null !== $options) {
      if (is_string($options)) {
        $options = $this->_loadConfig($options);
      } elseif ($options instanceof Zend_Config) {
        $options = $options->toArray();
      } elseif (!is_array($options)) {
        throw new Zend_Application_Exception('Invalid options provided; must be location of config file, a config object, or an array');
      }
      $this->setOptions($options);
    }
  }
  /**
   * Retrieve current environment
   *
   * @return string
   */
  public function getEnvironment()
  {
    return $this->_environment;
  }
  /**
   * Retrieve autoloader instance
   *
   * @return Zend_Loader_Autoloader
   */
  public function getAutoloader()
  {
    return $this->_autoloader;
  }
  /**
   * Set application options
   *
   * @param array $options
   * @throws Zend_Application_Exception When no bootstrap path is provided
   * @throws Zend_Application_Exception When invalid bootstrap information are provided
   * @return Zend_Application
   */
  public function setOptions(array $options)
  {
    if (!empty($options['config'])) {
      if (is_array($options['config'])) {
        $_options = array();
        foreach ($options['config'] as $tmp) {
          $_options = $this->mergeOptions($_options, $this->_loadConfig($tmp));
        }
        $options = $this->mergeOptions($_options, $options);
      } else {
        $options = $this->mergeOptions($this->_loadConfig($options['config']), $options);
      }
    }
    $this->_options = $options;
    $options = array_change_key_case($options, CASE_LOWER);
    $this->_optionKeys = array_keys($options);
    if (!empty($options['phpsettings'])) {
      $this->setPhpSettings($options['phpsettings']);
    }
    if (!empty($options['includepaths'])) {
      $this->setIncludePaths($options['includepaths']);
    }
    if (!empty($options['autoloadernamespaces'])) {
      $this->setAutoloaderNamespaces($options['autoloadernamespaces']);
    }
    if (!empty($options['autoloaderzfpath'])) {
      $autoloader = $this->getAutoloader();
      if (method_exists($autoloader, 'setZfPath')) {
        $zfPath  = $options['autoloaderzfpath'];
        $zfVersion = !empty($options['autoloaderzfversion'])
              ? $options['autoloaderzfversion']
              : 'latest';
        $autoloader->setZfPath($zfPath, $zfVersion);
      }
    }
    if (!empty($options['bootstrap'])) {
      $bootstrap = $options['bootstrap'];
      if (is_string($bootstrap)) {
        $this->setBootstrap($bootstrap);
      } elseif (is_array($bootstrap)) {
        if (empty($bootstrap['path'])) {
          throw new Zend_Application_Exception('No bootstrap path provided');
        }
        $path = $bootstrap['path'];
        $class = null;
        if (!empty($bootstrap['class'])) {
          $class = $bootstrap['class'];
        }
        $this->setBootstrap($path, $class);
      } else {
        throw new Zend_Application_Exception('Invalid bootstrap information provided');
      }
    }
    return $this;
  }
  /**
   * Retrieve application options (for caching)
   *
   * @return array
   */
  public function getOptions()
  {
    return $this->_options;
  }
  /**
   * Is an option present?
   *
   * @param string $key
   * @return bool
   */
  public function hasOption($key)
  {
    return in_array(strtolower($key), $this->_optionKeys);
  }
  /**
   * Retrieve a single option
   *
   * @param string $key
   * @return mixed
   */
  public function getOption($key)
  {
  }
  /**
   * Merge options recursively
   *
   * @param array $array1
   * @param mixed $array2
   * @return array
   */
  public function mergeOptions(array $array1, $array2 = null)
  {
    if (is_array($array2)) {
      foreach ($array2 as $key => $val) {
        if (is_array($array2[$key])) {
          $array1[$key] = (array_key_exists($key, $array1) && is_array($array1[$key]))
                 ? $this->mergeOptions($array1[$key], $array2[$key])
                 : $array2[$key];
        } else {
          $array1[$key] = $val;
        }
      }
    }
    return $array1;
  }
  /**
   * Set PHP configuration settings
   *
   * @param array $settings
   * @param string $prefix Key prefix to prepend to array values (used to map . separated INI values)
   * @return Zend_Application
   */
  public function setPhpSettings(array $settings, $prefix = '')
  {
    foreach ($settings as $key => $value) {
      $key = empty($prefix) ? $key : $prefix . $key;
      if (is_scalar($value)) {
        ini_set($key, $value);
      } elseif (is_array($value)) {
        $this->setPhpSettings($value, $key . '.');
      }
    }
    return $this;
  }
  /**
   * Set include path
   *
   * @param array $paths
   * @return Zend_Application
   */
  public function setIncludePaths(array $paths)
  {
    $path = implode(PATH_SEPARATOR, $paths);
    set_include_path($path . PATH_SEPARATOR . get_include_path());
    return $this;
  }
  /**
   * Set autoloader namespaces
   *
   * @param array $namespaces
   * @return Zend_Application
   */
  public function setAutoloaderNamespaces(array $namespaces)
  {
    $autoloader = $this->getAutoloader();
    foreach ($namespaces as $namespace) {
      $autoloader->registerNamespace($namespace);
    }
    return $this;
  }
  /**
   * Set bootstrap path/class
   *
   * @param string $path
   * @param string $class
   * @return Zend_Application
   */
  public function setBootstrap($path, $class = null)
  {
    // setOptions() can potentially send a null value; specify default
    // here
    if (null === $class) {
      $class = 'Bootstrap';
    }
    if (!class_exists($class, false)) {
      require_once $path;
      if (!class_exists($class, false)) {
        throw new Zend_Application_Exception('Bootstrap class not found');
      }
    }
    $this->_bootstrap = new $class($this);
    if (!$this->_bootstrap instanceof Zend_Application_Bootstrap_Bootstrapper) {
      throw new Zend_Application_Exception('Bootstrap class does not implement Zend_Application_Bootstrap_Bootstrapper');
    }
    return $this;
  }
  /**
   * Get bootstrap object
   *
   * @return Zend_Application_Bootstrap_BootstrapAbstract
   */
  public function getBootstrap()
  {
    if (null === $this->_bootstrap) {
      $this->_bootstrap = new Zend_Application_Bootstrap_Bootstrap($this);
    }
    return $this->_bootstrap;
  }
  /**
   * Bootstrap application
   *
   * @param null|string|array $resource
   * @return Zend_Application
   */
  public function bootstrap($resource = null)
  {
    $this->getBootstrap()->bootstrap($resource);
    return $this;
  }
  /**
   * Run the application
   *
   * @return void
   */
  public function run()
  {
    $this->getBootstrap()->run();
  }
  /**
   * Load configuration file of options
   *
   * @param string $file
   * @throws Zend_Application_Exception When invalid configuration file is provided
   * @return array
   */
  protected function _loadConfig($file)
  {
    $environment = $this->getEnvironment();
    $suffix   = pathinfo($file, PATHINFO_EXTENSION);
    $suffix   = ($suffix === 'dist')
           ? pathinfo(basename($file, ".$suffix"), PATHINFO_EXTENSION)
           : $suffix;
    switch (strtolower($suffix)) {
      case 'ini':
        $config = new Zend_Config_Ini($file, $environment);
        break;
      case 'xml':
        $config = new Zend_Config_Xml($file, $environment);
        break;
      case 'json':
        $config = new Zend_Config_Json($file, $environment);
        break;
      case 'yaml':
      case 'yml':
        $config = new Zend_Config_Yaml($file, $environment);
        break;
      case 'php':
      case 'inc':
        $config = include $file;
        if (!is_array($config)) {
          throw new Zend_Application_Exception('Invalid configuration file provided; PHP file does not return array value');
        }
        return $config;
        break;
      default:
        throw new Zend_Application_Exception('Invalid configuration file provided; unknown config type');
    }
    return $config->toArray();
  }
}

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
PHP+FLASH实现上传文件进度条相关文件 下载
Jul 21 PHP
php操作sqlserver关于时间日期读取的小小见解
Nov 29 PHP
PHP 日志缩略名的创建函数代码
May 26 PHP
linux环境apache多端口配置虚拟主机的方法深入介绍
Jun 09 PHP
Smarty模板学习笔记之Smarty简介
May 20 PHP
解密ThinkPHP3.1.2版本之模块和操作映射
Jun 19 PHP
php使用unset()删除数组中某个单元(键)的方法
Feb 17 PHP
Yii2中cookie用法示例分析
Jul 18 PHP
thinkphp下MySQL数据库读写分离代码剖析
Apr 18 PHP
PHP自定义函数判断是否为Get、Post及Ajax提交的方法
Jul 27 PHP
PHP命名空间(namespace)原理与用法详解
Dec 11 PHP
PHP 范围解析操作符(::)用法分析【访问静态成员和类常量】
Apr 14 PHP
Zend Framework自定义Helper类相关注意事项总结
Mar 14 #PHP
Zend Framework教程之Bootstrap类用法概述
Mar 14 #PHP
如何解决PHP使用mysql_query查询超大结果集超内存问题
Mar 14 #PHP
Zend Framework教程之资源(Resources)用法实例详解
Mar 14 #PHP
PHP访问数据库集群的方法小结
Mar 14 #PHP
php 无限级分类 获取顶级分类ID
Mar 13 #PHP
PHP实现文件上传与下载实例与总结
Mar 13 #PHP
You might like
laravel安装和配置教程
2014/10/29 PHP
php获取客户端电脑屏幕参数的方法
2015/01/09 PHP
php将金额数字转化为中文大写
2015/07/09 PHP
Centos6.5和Centos7 php环境搭建方法
2016/05/27 PHP
PHP编写的图片验证码类文件分享
2016/06/06 PHP
一个简单的php MVC留言本实例代码(必看篇)
2016/09/22 PHP
php mysql操作mysql_connect连接数据库实例详解
2016/12/26 PHP
PHP实现求解最长公共子串问题的方法
2017/11/17 PHP
Yii框架使用PHPExcel导出Excel文件的方法分析【改进版】
2019/07/24 PHP
在模板页面的js使用办法
2010/04/01 Javascript
jQuery中add实现同时选择两个id对象
2010/10/22 Javascript
在浏览器中实现图片粘贴的jQuery插件-- pasteimg使用指南
2014/12/29 Javascript
jQuery中scrollLeft()方法用法实例
2015/01/16 Javascript
JavaScript中split与join函数的进阶使用技巧
2016/05/03 Javascript
jquery实现无刷新验证码的简单实例
2016/05/19 Javascript
BootStrap中按钮点击后被禁用按钮的最佳实现方法
2016/09/23 Javascript
基于JavaScript实现全选、不选和反选效果
2017/02/15 Javascript
Angularjs 双向绑定时字符串的转换成数字类型的问题
2017/06/12 Javascript
JS获取url参数,JS发送json格式的POST请求方法
2018/03/29 Javascript
vue和webpack打包项目相对路径修改的方法
2018/06/15 Javascript
webstorm中配置Eslint的两种方式及差异比较详解
2018/10/19 Javascript
vuex如何重置所有state(可定制)
2019/01/17 Javascript
微信小程序实现拍照画布指定区域生成图片
2019/07/18 Javascript
Vue+Element UI+vue-quill-editor富文本编辑器及插入图片自定义
2019/08/20 Javascript
JavaScript图像放大镜效果实现方法详解
2020/06/28 Javascript
Python PyAutoGUI模块控制鼠标和键盘实现自动化任务详解
2018/09/04 Python
django-filter和普通查询的例子
2019/08/12 Python
详解Python绘图Turtle库
2019/10/12 Python
三个python爬虫项目实例代码
2019/12/28 Python
用缩写的指针比较"if(p)" 检查空指针是否可靠?如果空指针的内部表达不是0会怎么样?
2014/01/05 面试题
服装仓管员岗位职责
2014/06/17 职场文书
英语专业求职信
2014/07/08 职场文书
男方婚礼答谢词
2015/01/20 职场文书
饭店服务员岗位职责
2015/02/09 职场文书
Django migrate报错的解决方案
2021/05/20 Python
MYSQL数据库使用UTF-8中文编码乱码的解决办法
2021/05/26 MySQL