0

0

Getting started writing ZF2 modules_PHP教程

php中文网

php中文网

发布时间:2016-07-13 17:16:57

|

1622人浏览过

|

来源于php中文网

原创

 

Getting started writing ZF2 modules

During ZendCon this year, we released 2.0.0beta1 of Zend Framework. The key story in the release is the creation of a new MVC layer, and to sweeten the story, the addition of a modular application architecture.

"Modular? What's that mean?" For ZF2, "modular" means that your application is built of one or more "modules". In a lexicon agreed upon during our IRC meetings, a module is a collection of code and other files that solves a specific atomic problem of the application or website.

立即学习PHP免费学习笔记(深入)”;

As an example, consider a typical corporate website in a technical arena. You might have:

  • A home page
  • Product and other marketing pages
  • Some forums
  • A corporate blog
  • A knowledge base/FAQ area
  • Contact forms

These can be divided into discrete modules:

  • A "pages" modules for the home page, product, and marketing pages
  • A "forum" module
  • A "blog" module
  • An "faq" or "kb" module
  • A "contact" module

Furthermore, if these are developed well and discretely, they can be re-used between different applications!

So, let's dive into ZF2 modules!

What is a module?

In ZF2, a module is simply a namespaced directory, with a single "Module" class under it; no more, and no less, is required.

So, as an example:

<span modules fooblog module.php foopages></span>

The above shows two modules, "FooBlog" and "FooPages". The "Module.php" file under each contains a single "Module" class, namespaced per the module: FooBlog\Module andFooPages\Module, respectively.

This is the one and only requirement of modules; you can structure them however you want from here. However, we do have a recommended directory structure:

<span modules spindoctor module.php configs module.config.php public images css spin-doctor.css js spin-doctor.js src controller spindoctorcontroller.php discjockeycontroller.php form request.php tests bootstrap.php phpunit.xml spindoctorcontrollertest.php discjockeycontrollertest.php></span>

The important bits from above:

  • Configuration goes in a "configs" directory.
  • Public assets, such as javascript, CSS, and images, go in a "public" directory.
  • PHP source code goes in a "src" directory; code under that directory should follow PSR-0 standard structure.
  • Unit tests should go in a "tests" directory, which should also contain your PHPUnit configuration and bootstrapping.

Again, the above is simply a recommendation. Modules in that structure clearly dileneate the purpose of each subtree, allowing developers to easily introspect them.

The Module class

Now that we've discussed the minimum requirements for creating a module and its structure, let's discuss the minimum requirement: the Module class.

The module class, as noted previously, should exist in the module's namespace. Usually this will be equivalent to the module's directory name. Beyond that, however, there are no real requirements, other than the constructor should not require any arguments.

<span lang="php">
namespace FooBlog;

class Module
{
}
</span>

So, what do module classes do, then?

The module manager (class Zend\Module\Manager) fulfills three key purposes:

  • It aggregates the enabled modules (allowing you to loop over the classes manually).
  • It aggregates configuration from each module.
  • It triggers module initialization, if any.

I'm going to skip the first item and move directly to the configuration aspect.

Most applications require some sort of configuration. In an MVC application, this may include routing information, and likely some dependency injection configuration. In both cases, you likely don't want to configure anything until you have the full configuration available -- which means all modules must be loaded.

The module manager does this for you. It loops over all modules it knows about, and then merges their configuration into a single configuration object. To do this, it checks each Module class for a getConfig() method.

The getConfig() method simply needs to return an array or Traversable object. This data structure should have "environments" at the top level -- the "production", "staging", "testing", and "development" keys that you're used to with ZF1 and Zend_Config. Once returned, the module manager merges it with its master configuration so you can grab it again later.

Typically, you should provide the following in your configuration:

  • Dependency Injection configuration
  • Routing configuration
  • If you have module-specific configuration that falls outside those, the module-specific configuration. We recommend namespacing these keys after the module name: foo_blog.apikey = "..."

The easiest way to provide configuration? Define it as an array, and return it from a PHP file -- usually your configs/module.config.php file. Then your getConfig() method can be quite simple:

<span lang="php">
public function getConfig()
{
    return include __DIR__ . '/configs/module.config.php';
}
</span>

In the original bullet points covering the purpose of the module manager, the third bullet point was about module initialization. Quite often you may need to provide additional initialization once the full configuration is known and the application is bootstrapped -- meaning the router and locator are primed and ready. Some examples of things you might do:

  • Setup event listeners. Often, these require configured objects, and thus need access to the locator.
  • Configure plugins. Often, you may need to inject plugins with objects managed by the locator. As an example, the url() view helper needs a configured router in order to work.

The way to do these tasks is to subscribe to the bootstrap object's "bootstrap" event:

<span lang="php">
$events = StaticEventManager::getInstance();
$events->attach('bootstrap', 'bootstrap', array($this, 'doMoarInit'));
</span>

That event gets the application and module manager objects as parameters, which gives you access to everything you might possibly need.

ResearchFlow
ResearchFlow

专为学术研究和深度信息探索设计的AI学术研究工具

下载

The question is: where do I do this? The answer: the module manager will call a Module class's init() method if found. So, with that in hand, you'll have the following:

<span lang="php">
namespace FooBlog;

use Zend\EventManager\StaticEventManager,
    Zend\Module\Manager as ModuleManager

class Module
{
    public function init(ModuleManager $manager)
    {
        $events = StaticEventManager::getInstance();
        $events->attach('bootstrap', 'bootstrap', array($this, 'doMoarInit'));
    }
    
    public function doMoarInit($e)
    {
        $application = $e->getParam('application');
        $modules     = $e->getParam('modules');
        
        $locator = $application->getLocator();
        $router  = $application->getRouter();
        $config  = $modules->getMergedConfig();
        
        // do something with the above!
    }
}
</span>

As you can see, when the bootstrap event is triggered, you have access to theZend\Mvc\Application instance as well as the Zend\Module\Manager instance, giving you access to your configured locator and router, as well as merged configuration from all modules! Basically, you have everything you could possibly want to access right at your fingertips.

What else might you want to do during init()? One very, very important thing: setup autoloading for the PHP classes in your module!

ZF2 offers several different autoloaders to provide different strategies geared towards ease of development to production speed. For beta1, they were refactored slightly to make them even more useful. The primary change was to the AutoloaderFactory, to allow it to keep single instances of each autoloader it handles, and thus allow specifying additional configuration for each. As such, this means that if you use theAutoloaderFactory, you'll only ever have one instance of a ClassMapAutoloader orStandardAutoloader -- and this means each module can simply add to their configuration.

As such, here's a typical autoloading boilerplate:

<span lang="php">
namespace FooBlog;

use Zend\EventManager\StaticEventManager,
    Zend\Loader\AutoloaderFactory,
    Zend\Module\Manager as ModuleManager

class Module
{
    public function init(ModuleManager $manager)
    {
        $this->initializeAutoloader();
        // ...
    }
    
    public function initializeAutoloader()
    {
        AutoloaderFactory::factory(array(
            'Zend\Loader\ClassMapAutoloader' => array(
                include __DIR__ .  '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' .  __NAMESPACE__,
                ),
            ),
        ));
    }
</span>

During development, you can have autoload_classmap.php return an empty array, but then during production, you can generate it based on the classes in your module. By having the StandardAutoloader in place, you have a backup solution until the classmap is updated.

Now that you know how your module can provide configuration, and how it can tie into bootstrapping, I can finally cover the original point: the module manager aggregates enabled modules. This allows modules to "opt-in" to additional features of an application. As an example, you could make modules "ACL aware", and have a "security" module grab module-specific ACLs:

<span lang="php">
    public function initializeAcls($e)
    {
        $this->acl = new Acl;
        $modules   = $e->getParam('modules');
        foreach ($modules->getLoadedModules() as $module) {
            if (!method_exists($module, 'getAcl')) {
                continue;
            }
            $this->processModuleAcl($module->getAcl());
        }
    }
</span>

This is an immensely powerful technique, and I'm sure we'll see a lot of creative uses for it in the future!

Composing modules into your application

So, writing modules should be easy, right? Right?!?!?

The other trick, then, is telling the module manager about your modules. There's a reason I've used phrases like, "enabled modules" "modules it [the module manager] knows about," and such: the module manager is opt-in. You have to tell it what modules it will load.

Some may say, "Why? Isn't that against rapid application development?" Well, yes and no. Consider this: what if you discover a security issue in a module? You could remove it entirely from the repository, sure. Or you could simply update the module manager configuration so it doesn't load it, and then start testing and patching it in place; when done, all you need to do is re-enable it.

Loading modules is a two-stage process. First, the system needs to know where and how to locate module classes. Second, it needs to actually load them. We have two components surrounding this:

  • Zend\Loader\ModuleAutoloader
  • Zend\Module\Manager

The ModuleAutoloader takes a list of paths, or associations of module names to paths, and uses that information to resolve Module classes. Often, modules will live under a single directory, and configuration is as simple as this:

<span lang="php">
$loader = new Zend\Loader\ModuleAutoloader(array(
    __DIR__ . '/../modules',
));
$loader->register();
</span>

You can specify multiple paths, or explicit module:directory pairs:

<span lang="php">
$loader = new Zend\Loader\ModuleAutoloader(array(
    __DIR__ . '/../vendors',
    __DIR__ . '/../modules',
    'User' => __DIR__ . '/../vendors/EdpUser-0.1.0',
));
$loader->register();
</span>

In the above, the last will look for a User\Module class in the file vendors/EdpUser-0.1.0/Module.php, but expect that modules found in the other two directories specified will always have a 1:1 correlation between the directory name and module namespace.

Once you have your ModuleAutoloader in place, you can invoke the module manager, and inform it of what modules it should load. Let's say that we have the following modules:

<span modules application module.php security vendors fooblog spindoctor></span>

and we wanted to load the "Application", "Security", and "FooBlog" modules. Let's also assume we've configured the ModuleAutoloader correctly already. We can then do this:

<span lang="php">
$manager = new Zend\Module\Manager(array(
    'Application',
    'Security',
    'FooBlog',
));
$manager->loadModules();
</span>

We're done! If you were to do some profiling and introspection at this point, you'd see that the "SpinDoctor" module will not be represented -- only those modules we've configured.

To make the story easy and reduce boilerplate, the ZendSkeletonApplication repository provides a basic bootstrap for you in public/index.php. This file consumesconfigs/application.config.php, in which you specify two keys, "module_paths" and "modules":

<span lang="php">
return array(
    'module_paths' => array(
        realpath(__DIR__ . '/../modules'),
        realpath(__DIR__ . '/../vendors'),
    ),
    'modules' => array(
        'Application',
        'Security',
        'FooBlog',
    ),
);
</span>

It doesn't get much simpler at this point.

Tips and Tricks

One trick I've learned deals with how and when modules are loaded. In the previous section, I introduced the module manager and how it's notified of what modules we're composing in this application. One interesting thing is that modules are processed in the order in which they are provided in your configuration. This means that the configuration is merged in that order as well.

The trick then, is this: if you want to override configuration settings, don't do it in the modules; create a special module that loads last to do it!

So, consider this module class:

<span lang="php">
namespace Local;

class Module
{
    public function getConfig()
    {
        return include __DIR__ . '/configs/module.config.php';
    }
}
</span>

We then create a configuration file in configs/module.config.php, and specify any configuration overrides we want there!

<span lang="php">
return array(
    'production' => array(
        'di' => 'alias' => array(
            'view' => 'My\Custom\Renderer',
        ),
    ),
);
</span>

Then, in our configs/application.config.php, we simply enable this module as the last in our list:

<span lang="php">
return array(
    // ...
    'modules' => array(
        'Application',
        'Security',
        'FooBlog',
        'Local',
    ),
);
</span>

Done!

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/626649.htmlTechArticleGetting started writing ZF2 modules DuringZendConthis year, wereleased 2.0.0beta1ofZend Framework. The key story in the release is the creation of a new MVC layer, and to sweeten t...

相关文章

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
pixiv网页版官网登录与阅读指南_pixiv官网直达入口与在线访问方法
pixiv网页版官网登录与阅读指南_pixiv官网直达入口与在线访问方法

本专题系统整理pixiv网页版官网入口及登录访问方式,涵盖官网登录页面直达路径、在线阅读入口及快速进入方法说明,帮助用户高效找到pixiv官方网站,实现便捷、安全的网页端浏览与账号登录体验。

1044

2026.02.13

微博网页版主页入口与登录指南_官方网页端快速访问方法
微博网页版主页入口与登录指南_官方网页端快速访问方法

本专题系统整理微博网页版官方入口及网页端登录方式,涵盖首页直达地址、账号登录流程与常见访问问题说明,帮助用户快速找到微博官网主页,实现便捷、安全的网页端登录与内容浏览体验。

334

2026.02.13

Flutter跨平台开发与状态管理实战
Flutter跨平台开发与状态管理实战

本专题围绕Flutter框架展开,系统讲解跨平台UI构建原理与状态管理方案。内容涵盖Widget生命周期、路由管理、Provider与Bloc状态管理模式、网络请求封装及性能优化技巧。通过实战项目演示,帮助开发者构建流畅、可维护的跨平台移动应用。

213

2026.02.13

TypeScript工程化开发与Vite构建优化实践
TypeScript工程化开发与Vite构建优化实践

本专题面向前端开发者,深入讲解 TypeScript 类型系统与大型项目结构设计方法,并结合 Vite 构建工具优化前端工程化流程。内容包括模块化设计、类型声明管理、代码分割、热更新原理以及构建性能调优。通过完整项目示例,帮助开发者提升代码可维护性与开发效率。

35

2026.02.13

Redis高可用架构与分布式缓存实战
Redis高可用架构与分布式缓存实战

本专题围绕 Redis 在高并发系统中的应用展开,系统讲解主从复制、哨兵机制、Cluster 集群模式及数据分片原理。内容涵盖缓存穿透与雪崩解决方案、分布式锁实现、热点数据优化及持久化策略。通过真实业务场景演示,帮助开发者构建高可用、可扩展的分布式缓存系统。

111

2026.02.13

c语言 数据类型
c语言 数据类型

本专题整合了c语言数据类型相关内容,阅读专题下面的文章了解更多详细内容。

77

2026.02.12

雨课堂网页版登录入口与使用指南_官方在线教学平台访问方法
雨课堂网页版登录入口与使用指南_官方在线教学平台访问方法

本专题系统整理雨课堂网页版官方入口及在线登录方式,涵盖账号登录流程、官方直连入口及平台访问方法说明,帮助师生用户快速进入雨课堂在线教学平台,实现便捷、高效的课程学习与教学管理体验。

17

2026.02.12

豆包AI网页版入口与智能创作指南_官方在线写作与图片生成使用方法
豆包AI网页版入口与智能创作指南_官方在线写作与图片生成使用方法

本专题汇总豆包AI官方网页版入口及在线使用方式,涵盖智能写作工具、图片生成体验入口和官网登录方法,帮助用户快速直达豆包AI平台,高效完成文本创作与AI生图任务,实现便捷智能创作体验。

813

2026.02.12

PostgreSQL性能优化与索引调优实战
PostgreSQL性能优化与索引调优实战

本专题面向后端开发与数据库工程师,深入讲解 PostgreSQL 查询优化原理与索引机制。内容包括执行计划分析、常见索引类型对比、慢查询优化策略、事务隔离级别以及高并发场景下的性能调优技巧。通过实战案例解析,帮助开发者提升数据库响应速度与系统稳定性。

97

2026.02.12

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号