zf2相关的网站推荐一个http://avnpc.com
资料汇总http://avnpc.com/pages/zf2-summary
Zend Framework 2.0的Mvc结构及启动流程分析http://avnpc.com/pages/zf2-mvc-process
zf2中文文档:https://zf2-cn.readthedocs.org/en/latest/(翻译了部分)
本笔记只是学习ZF2及记录zf2的一些技术要点,初期不涉及实际项目,如需ZF2项目推荐http://avnpc.com/pages/eva-engine
先从ZF2的启动开始,项目搭建之类的可以看上面推荐网站里找下教程
本笔记以ZF2的ZendSkeletonApplication实例程序为基础https://github.com/zendframework/ZendSkeletonApplication
目录结构是从public目录里的index.php作为网站入口的
index.php作为网站入口注册了类自动加载器,并运行了ZendMvcApplication来启动网站业务流程,主要流程如下
/** * This makes our life easier when dealing with paths. Everything is relative *这使我们的生存周期内更容易处理路径,一切都是相对的 * to the application root now. 现在到应用根目录 */ chdir(dirname(__DIR__)); // Setup autoloading 设置自动加载 require 'init_autoloader.php'; // Run the application! 运行应用程序 ZendMvcApplication::init(require 'config/application.config.php')->run();
init_autoloader.php主要是初始化类自动加载,主要流程如下
1 // 如果./vendor/autoload.php文件存在,则使用autoload.php文件返回的类自动加载器 2 if (file_exists('vendor/autoload.php')) { 3 $loader = include 'vendor/autoload.php'; 4 } 5 6 $zf2Path = false; 7 8 9 if (is_dir('vendor/ZF2/library')) { 10 $zf2Path = 'vendor/ZF2/library'; 11 } elseif (getenv('ZF2_PATH')) { // Suppodrt for ZF2_PATH environment variable or git submodule (支持ZF2_PATH环境变量或git子模块) 12 $zf2Path = getenv('ZF2_PATH'); 13 } elseif (get_cfg_var('zf2_path')) { // Support for zf2_path directive value (支持zf2_path指令值) 14 $zf2Path = get_cfg_var('zf2_path'); 15 } 16 17 // 18 if ($zf2Path) { 19 if (isset($loader)) { 20 // 如果autoload.php存在则调用其add方法增加Zend库 21 $loader->add('Zend', $zf2Path); 22 } else { 23 //AutoloaderFactory类主要是通过spl_autoload_register函数注册autoload方法来实现自动加载类,类的命名结构需遵循PSR-0标准,有兴趣的可以研究下 24 include $zf2Path . '/Zend/Loader/AutoloaderFactory.php'; 25 ZendLoaderAutoloaderFactory::factory(array( 26 'ZendLoaderStandardAutoloader' => array( 27 'autoregister_zf' => true 28 ) 29 )); 30 } 31 } 32 33 if (!class_exists('ZendLoaderAutoloaderFactory')) { 34 throw new RuntimeException('Unable to load ZF2. Run `php composer.phar install` or define a ZF2_PATH environment variable.'); 35 }
ZendMvcApplication初始化运行流程
/** * 快捷、简便初始化Application的静态方法 * * 如果你使用init()方法,你将不能在你的服务管理配置中指定一个服务名称为 'ApplicationConfig' 的服务. 这个名称 * 是来自 application.config.php 的保留数组 * * 以下服务只能从application.config.php覆盖: * * - ModuleManager * - SharedEventManager * - EventManager & ZendEventManagerEventManagerInterface * * 所有其他服务在模块加载后配置,因此可以覆盖模块 * * @param array $configuration * @return Application */ public static function init($configuration = array()) { $smConfig = isset($configuration['service_manager']) ? $configuration['service_manager'] : array(); $serviceManager = new ServiceManager(new ServiceServiceManagerConfig($smConfig)); $serviceManager->setService('ApplicationConfig', $configuration); $serviceManager->get('ModuleManager')->loadModules(); return $serviceManager->get('Application')->bootstrap(); }