Zend Framework - 创建模块
在本章中,我们将学习如何在 Zend Framework 中创建基于 MVC 的模块。让我们创建一个名为 Tutorial 的模块来了解模块创建过程。
在 –myapp/module/Tutorial/src/ 目录中创建一个名为 Module 的新 PHP 类,并实现 ConfigProviderInterface。
将 Tutorial 设置为 Module 类的命名空间。
在 Module 类中编写一个公共函数 getConfig,并返回 Tutorial 模块的配置文件。
Module 类的完整代码如下 −
<?php namespace Tutorial; use Zend\ModuleManager\Feature\ConfigProviderInterface; class Module implements ConfigProviderInterface { public function getConfig() { return include __DIR__ . '/../config/module.config.php'; } }
使用以下代码在 composer.json 的 autoload 部分下配置 Tutorial 模块。
"autoload": { "psr-4": { "Application\": "module/Application/src/", "Tutorial\": "module/Tutorial/src/" } }
使用 composer update 命令更新应用程序,如下所示。
composer update
composer 命令将对应用程序进行必要的更改,并在命令提示符中显示日志,如下所示 −
Loading composer repositories with package information Updating dependencies (including require-dev) - Removing zendframework/zend-component-installer (0.3.0) - Installing zendframework/zend-component-installer (0.3.1) Downloading: 100% - Removing zendframework/zend-stdlib (3.0.1) - Installing zendframework/zend-stdlib (3.1.0) Loading from cache - Removing zendframework/zend-eventmanager (3.0.1) - Installing zendframework/zend-eventmanager (3.1.0) Downloading: 100% - Removing zendframework/zend-view (2.8.0) - Installing zendframework/zend-view (2.8.1) Loading from cache - Removing zendframework/zend-servicemanager (3.1.0) - Installing zendframework/zend-servicemanager (3.2.0) Downloading: 100% - Removing zendframework/zend-escaper (2.5.1) - Installing zendframework/zend-escaper (2.5.2) Loading from cache - Removing zendframework/zend-http (2.5.4) - Installing zendframework/zend-http (2.5.5) Loading from cache - Removing zendframework/zend-mvc (3.0.1) - Installing zendframework/zend-mvc (3.0.4) Downloading: 100% - Removing phpunit/phpunit (5.7.4) - Installing phpunit/phpunit (5.7.5) Downloading: 100% Writing lock file Generating autoload files
使用以下代码在 /config/ 中创建模块配置文件"module.config.php" −
<?php namespace Tutorial; use Zend\ServiceManager\Factory\InvokableFactory; use Zend\Router\Http\Segment; return [ 'controllers' => [ 'factories' => [Controller\TutorialController::class => InvokableFactory::class,], ], 'view_manager' => [ 'template_path_stack' => ['tutorial' => __DIR__ . '/../view',], ], ];
配置文件分为三部分,具体如下 −
控制器配置 − 指定模块内可用的控制器。
路由配置 − 指定模块中的控制器如何解析为 URL。
视图配置 − 指定与视图引擎相关的配置,例如视图的位置等。
在应用程序级配置文件 – myapp/config/modules.config.php 中配置 Tutorial 模块。
return ['Zend\Router', 'Zend\Validator', 'Application', 'Tutorial'];
通过在应用程序文件夹的根目录中执行 composer serve 来运行应用程序。
我们已经成功添加了一个新模块,但我们仍然需要添加 Controller、Routing 和 Views 才能成功运行 Tutorial 模块。