Getting started writing ZF2 modules_php tutorial

Source: Internet
Author: User
Tags configuration settings php source code knowledge base zend framework
< span="">

Getting started writing ZF2 modules

During Zendcon This year, we released 2.0.0beta1 of the 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 appli cation architecture.

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

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

    • A Home Page
    • Product and other marketing pages
    • Some Forums
    • A Corporate Blog
    • A Knowledge Base/faq Area
    • Contact forms

These can 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 is 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 was simply a namespaced directory, with a single "module" class under it; No more, and no less, is required.

So, as an example:

< span="">

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

The one and only requirement of modules; You can structure them however your want from here. However, we do have a recommended directory structure:

< 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 this 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 this 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 requi Rement:the Module class.

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

namespace FooBlog;class Module{}

So, what does module classes do and then?

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

    • It aggregates the enabled modules (allowing you-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 a 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 and the full configuration available--which means All modules must is loaded.

The module manager does. It loops over all modules it knows on, and then merges their configuration to a single Configuration object. To does this, the 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 has "environments" at the top level--the "production", "staging", "testing", and "developmen T "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, should provide the following in your configuration:

    • Dependency Injection Configuration
    • Routing Configuration
    • If you had 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 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 is quite simple:

public function getConfig(){    return include __DIR__ . '/configs/module.config.php';}

In the original bullet points covering the purpose of the module manager, the third bullet point is about module Initiali Zation. Quite often need to provide additional initialization once the full configuration is known and the application is bootstrapped-meaning the router and locator is 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, 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 the-do these tasks are to subscribe to the Bootstrap object ' s "Bootstrap" event:

$events = StaticEventManager::getInstance();$events->attach('bootstrap', 'bootstrap', array($this, 'doMoarInit'));

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

The question Is:where do I does this? The Answer:the module manager would call a module class ' s init() method if found. So, with the to hand, you'll have the following:

namespace fooblog;use Zend\eventmanager\staticeventmanager, Zend\Module\ Manager as Modulemanagerclass module{public function init (Modulemanager $manager) {$events = Staticeventman        Ager::getinstance ();    $events->attach (' Bootstrap ', ' Bootstrap ', Array ($this, ' domoarinit '));        The 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! }}

As you can see, if the bootstrap event is a triggered, you have access to the Zend\Mvc\Application instance as well as Zend\Module\Manager the instance, Giving you access to your configured locator and router, as-well-merged configuration from all modules! Basically, you are 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 is AutoloaderFactory to the-the to-allow it-keep single instances of each autoloader it handles, and thus allow SP Ecifying additional configuration for each. As such, this means so if you use the, you'll only AutoloaderFactory ever has one instance of a ClassMapAutoloader or StandardAutoloader --and this means each Module can simply add to their configuration.

As such, here's a typical autoloading boilerplate:

namespace fooblog;use Zend\eventmanager\staticeventmanager, Zend\Loader\    Autoloaderfactory, Zend\module\manager as Modulemanagerclass module{public function init (Modulemanager $manager)        {$this->initializeautoloader ();        // ...    } Public Function Initializeautoloader () {autoloaderfactory::factory (Array (' Zend\loader\classmapautol  Oader ' = = Array (include __dir__. '/autoload_classmap.php ',), ' zend\loader\standardautoloader ' = = Array (' namespace s ' = = Array (__namespace__ = __dir__.  '/src/'.    __namespace__,),)); }

During development, you can have autoload_classmap.php a return an empty array, and then During production, you can generate it based on the Classes in your module. StandardAutoloaderby has the in place and you had a backup solution until the Classmap is updated.

Now so you know how your module can provide configuration, and how it can tie into bootstrapping, I can finally cover th E 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 has a "security" module grab module-specific ACLs:

    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());        }    }

This was 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 is easy, right? Right?!?!?

The other trick, then, was 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 mo Dule Manager is opt-in. You have a to-tell it what modules it would 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 did, all you need to does is re-enable it.

Loading modules is a two-stage process. First, the system needs to know where and so to locate module classes. Second, it needs to actually load them. We have the following 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 Clas Ses. Often, modules would live under a single directory, and configuration are as simple as this:

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

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

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

In the above, the last would look- User\Module vendors/EdpUser-0.1.0/Module.php for-a class in the file, but expect this modules found in the other of the Direc Tories specified would always have a 1:1 correlation between the directory Name and module namespace.

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

< 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 does this:

$manager = new Zend\Module\Manager(array(    'Application',    'Security',    'FooBlog',));$manager->loadModules();

We ' re done! If you were to does some profiling and introspection at this point, you're ' d see that the ' Spindoctor ' module won't be repre sented--Only those modules we ' ve configured.

The stories easy and reduce boilerplate, the Zendskeletonapplication repository provides a basic bootstrap for you I N public/index.php . This file consumes configs/application.config.php , in which you specify the keys, "module_paths" and "modules":

return array(    'module_paths' => array(        realpath(__DIR__ . '/../modules'),        realpath(__DIR__ . '/../vendors'),    ),    'modules' => array(        'Application',        'Security',        'FooBlog',    ),);

It doesn ' t get much simpler at this point.

Tips and Tricks

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

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

So, consider the This module class:

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

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

return array(    'production' => array(        'di' => 'alias' => array(            'view' => 'My\Custom\Renderer',        ),    ),);

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

return array(    // ...    'modules' => array(        'Application',        'Security',        'FooBlog',        'Local',    ),);

done!

http://www.bkjia.com/PHPjc/626649.html www.bkjia.com true http://www.bkjia.com/PHPjc/626649.html techarticle Getting started writing ZF2 modules Duringzendconthis year, wereleased 2.0.0beta1ofzend Framework. The key stories in the release are the creation of a new MVC layer, and to sweeten t ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.