首页  >  文章  >  php教程  >  开始编写 ZF2 模块

开始编写 ZF2 模块

WBOY
WBOY原创
2016-06-13 10:17:461075浏览

 

开始编写 ZF2 模块

在今年的 ZendCon 期间,我们发布了 Zend Framework 2.0.0beta1。该版本中的关键故事是创建新的 MVC 层,并且为了使故事更有趣,还添加了模块化应用程序架构。

“模块化?这是什么意思?”对于 ZF2,“模块化”意味着您的应用程序由一个或多个“模块”构建。在我们的 IRC 会议期间商定的词汇中,模块是解决应用程序或网站的特定原子问题的代码和其他文件的集合。

举个例子,考虑技术领域的典型公司网站。您可能有:

  • 主页
  • 产品和其他营销页面
  • 一些论坛
  • 企业博客
  • 知识库/常见问题解答区
  • 联系表格

这些可以分为离散模块:

  • 主页、产品和营销页面的“页面”模块
  • “论坛”模块
  • “博客”模块
  • “常见问题解答”或“知识库”模块
  • “联系人”模块

此外,如果这些开发得好且离散,它们可以在不同的应用程序之间重复使用

那么,让我们深入了解 ZF2 模块!

什么是模块?

在 ZF2 中,模块只是一个命名空间目录,其下有一个“Module”类;不多也不少。

所以,举个例子:

<span modules/
    FooBlog/
        Module.php
    FooPages/
        Module.php
</span>

上面显示了两个模块,“FooBlog”和“FooPages”。每个文件下的“Module.php”文件都包含一个“Module”类,按模块命名:分别为FooBlogModuleFooPagesModule

这是模块唯一的要求;您可以从这里按照您想要的方式构建它们。但是,我们确实有一个推荐目录结构:

<span modules/
    SpinDoctor/
        Module.php
        configs/
            module.config.php
        public/
            images/
            css/
                spin-doctor.css
            js/
                spin-doctor.js
        src/
            SpinDoctor/
                Controller/
                    SpinDoctorController.php
                    DiscJockeyController.php
                Form/
                    Request.php
        tests/
            bootstrap.php
            phpunit.xml
            SpinDoctor/
                Controller/
                    SpinDoctorControllerTest.php
                    DiscJockeyControllerTest.php
</span>

上面的重要部分:

  • 配置位于“configs”目录中。
  • 公共资产,例如 javascript、CSS 和图像,位于“公共”目录中。
  • PHP 源代码位于“src”目录中;该目录下的代码应遵循 PSR-0 标准结构。
  • 单元测试应该放在“tests”目录中,该目录还应该包含您的 PHPUnit 配置和引导。

再次强调,以上只是建议。该结构中的模块清楚地扩展了每个子树的用途,使开发人员可以轻松地内省它们。

模块类

现在我们已经讨论了创建模块及其结构的最低要求,让我们讨论最低要求:Module 类。

如前所述,模块类应该存在于模块的命名空间中。通常这相当于模块的目录名称。然而,除此之外,除了构造函数不应该需要任何参数之外,没有真正的要求。

<span <code lang="php">
namespace FooBlog;

class Module
{
}
</code></span>

那么,模块类做什么呢?

模块管理器(类ZendModuleManager)实现三个关键目的:

  • 它聚合启用的模块(允许您手动循环类)。
  • 它聚合每个模块的配置。
  • 它会触发模块初始化(如果有)。

我将跳过第一项,直接进入配置方面。

大多数应用程序都需要某种配置。在 MVC 应用程序中,这可能包括路由信息,以及可能的一些依赖项注入配置。在这两种情况下,您可能不想配置任何内容,直到拥有可用的完整配置 - 这意味着必须加载所有模块。

模块管理器会为您完成此操作。它循环遍历它知道的所有模块,然后将它们的配置合并到单个配置对象中。为此,它会检查每个模块类的 getConfig() 方法。

getConfig() 方法只需要返回一个 arrayTraversable 对象。此数据结构应该在顶层有“环境”——您习惯使用 ZF1 和 Zend_Config 的“生产”、“登台”、“测试”和“开发”键。返回后,模块管理器会将其与其主配置合并,以便您稍后可以再次获取它。

通常,您应该在配置中提供以下内容:

  • 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 <code lang="php">
public function getConfig()
{
    return include __DIR__ . '/configs/module.config.php';
}
</code></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 <code lang="php">
$events = StaticEventManager::getInstance();
$events->attach('bootstrap', 'bootstrap', array($this, 'doMoarInit'));
</code></span>

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

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 <code 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!
    }
}
</code></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 <code 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__,
                ),
            ),
        ));
    }
</code></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 <code 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());
        }
    }
</code></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 <code lang="php">
$loader = new Zend\Loader\ModuleAutoloader(array(
    __DIR__ . '/../modules',
));
$loader->register();
</code></span>

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

<span <code lang="php">
$loader = new Zend\Loader\ModuleAutoloader(array(
    __DIR__ . '/../vendors',
    __DIR__ . '/../modules',
    'User' => __DIR__ . '/../vendors/EdpUser-0.1.0',
));
$loader->register();
</code></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/
        Module.php
vendors/
    FooBlog/
        Module.php
    SpinDoctor/
        Module.php
</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 <code lang="php">
$manager = new Zend\Module\Manager(array(
    'Application',
    'Security',
    'FooBlog',
));
$manager->loadModules();
</code></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 <code lang="php">
return array(
    'module_paths' => array(
        realpath(__DIR__ . '/../modules'),
        realpath(__DIR__ . '/../vendors'),
    ),
    'modules' => array(
        'Application',
        'Security',
        'FooBlog',
    ),
);
</code></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 <code lang="php">
namespace Local;

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

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

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

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

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

Done!

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