Advertisement
Google Ad Slot: content-top
Zend Create Module
Creating a Module in Zend Framework
Zend Framework is modular by design, which means your application can be organized into multiple self-contained modules, each with its own controllers, views, models, and configuration.
What is a Module?
A Module in Zend is like a mini-application. It can contain:
- Configuration
- Controllers
- Views
- Models
- Services
- Event Listeners
Modules make your app scalable, maintainable, and reusable.
Module Folder Structure
Each module should follow a consistent folder structure. Example:
module/ └── Blog/ ├── config/ │ └── module.config.php ├── src/ │ └── Module.php │ └── Controller/ │ └── IndexController.php ├── view/ │ └── blog/ │ └── index/ │ └── index.phtml
Steps to Create a Module
1. Create Folder
Create a new folder under /module:
mkdir module\Blog\src\Controller mkdir module\Blog\view\blog\index mkdir module\Blog\config
2. Create Module.php in (module\Blog\src\Module.php)
<?php
declare(strict_types=1);
namespace Blog;
use Laminas\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
}
3. Create module.config.php in (module\Blog\config\module.config.php)
<?php declare(strict_types=1); namespace Blog; use Laminas\Router\Http\Literal; use Laminas\ServiceManager\Factory\InvokableFactory; return [ 'router' => [ 'routes' => [ 'blog' => [ 'type' => Literal::class, 'options' => [ 'route' => '/blog', 'defaults' => [ 'controller' => Controller\IndexController::class, 'action' => 'index', ], ], ], ], ], 'controllers' => [ 'factories' => [ Controller\IndexController::class => InvokableFactory::class, ], ], 'view_manager' => [ 'template_path_stack' => [ 'blog' => __DIR__ . '/../view', ], ], ];
4. Create IndexController.php in (module\Blog\src\Controller\IndexController.php)
<?php
declare(strict_types=1);
namespace Blog\Controller;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\ViewModel;
class IndexController extends AbstractActionController
{
public function indexAction()
{
return new ViewModel(['message' => 'Welcome to Blog Module!']);
}
}
5. Create View File in (module/Blog/view/blog/index/index.phtml)
<h2><?= $this->escapeHtml($message) ?></h2>
6. Enable the Module
Add Blog to the config/modules.config.php file:
return [ 'Laminas\Router', 'Laminas\Validator', 'Application', 'Blog', // ✅ Add this line ];
7. Add Blog in composer.json
"autoload": {
"psr-4": {
"Application\\": "module/Application/src/",
"Blog\\": "module/Blog/src/"
}
},
8.Run composer dump
composer dump-autoload
Test
Visit: http://localhost/blog
<h2>Welcome to Blog Module!</h2>