搜尋
首頁後端開發php教程Getting started writing ZF2 modules_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.

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/
        Module.php
</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/
            SpinDoctor/
                Controller/
                    SpinDoctorController.php
                    DiscJockeyController.php
                Form/
                    Request.php
        tests/
            bootstrap.php
            phpunit.xml
            SpinDoctor/
                Controller/
                    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 <code lang="php">
namespace FooBlog;

class Module
{
}
</code></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 <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!

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...
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
PHP的目的:構建動態網站PHP的目的:構建動態網站Apr 15, 2025 am 12:18 AM

PHP用於構建動態網站,其核心功能包括:1.生成動態內容,通過與數據庫對接實時生成網頁;2.處理用戶交互和表單提交,驗證輸入並響應操作;3.管理會話和用戶認證,提供個性化體驗;4.優化性能和遵循最佳實踐,提升網站效率和安全性。

PHP:處理數據庫和服務器端邏輯PHP:處理數據庫和服務器端邏輯Apr 15, 2025 am 12:15 AM

PHP在數據庫操作和服務器端邏輯處理中使用MySQLi和PDO擴展進行數據庫交互,並通過會話管理等功能處理服務器端邏輯。 1)使用MySQLi或PDO連接數據庫,執行SQL查詢。 2)通過會話管理等功能處理HTTP請求和用戶狀態。 3)使用事務確保數據庫操作的原子性。 4)防止SQL注入,使用異常處理和關閉連接來調試。 5)通過索引和緩存優化性能,編寫可讀性高的代碼並進行錯誤處理。

您如何防止PHP中的SQL注入? (準備的陳述,PDO)您如何防止PHP中的SQL注入? (準備的陳述,PDO)Apr 15, 2025 am 12:15 AM

在PHP中使用預處理語句和PDO可以有效防範SQL注入攻擊。 1)使用PDO連接數據庫並設置錯誤模式。 2)通過prepare方法創建預處理語句,使用佔位符和execute方法傳遞數據。 3)處理查詢結果並確保代碼的安全性和性能。

PHP和Python:代碼示例和比較PHP和Python:代碼示例和比較Apr 15, 2025 am 12:07 AM

PHP和Python各有優劣,選擇取決於項目需求和個人偏好。 1.PHP適合快速開發和維護大型Web應用。 2.Python在數據科學和機器學習領域佔據主導地位。

PHP行動:現實世界中的示例和應用程序PHP行動:現實世界中的示例和應用程序Apr 14, 2025 am 12:19 AM

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP:輕鬆創建交互式Web內容PHP:輕鬆創建交互式Web內容Apr 14, 2025 am 12:15 AM

PHP可以輕鬆創建互動網頁內容。 1)通過嵌入HTML動態生成內容,根據用戶輸入或數據庫數據實時展示。 2)處理表單提交並生成動態輸出,確保使用htmlspecialchars防XSS。 3)結合MySQL創建用戶註冊系統,使用password_hash和預處理語句增強安全性。掌握這些技巧將提升Web開發效率。

PHP和Python:比較兩種流行的編程語言PHP和Python:比較兩種流行的編程語言Apr 14, 2025 am 12:13 AM

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP的持久相關性:它還活著嗎?PHP的持久相關性:它還活著嗎?Apr 14, 2025 am 12:12 AM

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具