Создание нового модуля ZF3 с ZendSkeletonModule

Я создал новый модуль через Git, используя ZendSkeletonModule:

git clone git://github.com/zendframework/ZendSkeletonModule.git Users

и сделал изменения в соответствии с новым именем модуля. Но, несмотря на это, это не работает, и я получаю 404 error occurred,

Название модуля User и вот файлы:

/module/Users/config/module.config.php
/module/Users/src/Module.php
/config/application.config.php
/config/modules.config.php
/composer.json

/module/Users/config/module.config.php

<?php
namespace Users;

use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;

return [
'router' => [
'routes' => [
'users' => [
'type'    => Literal::class,
'options' => [
// Change this to something specific to your module
'route'    => '/users',
'defaults' => [
'controller'    => Controller\IndexController::class,
'action'        => 'index',
],
],
'may_terminate' => true,
'child_routes' => [
// You can place additional routes that match under the
// route defined above here.
],
],
],
],
'controllers' => [
'factories' => [
Controller\IndexController::class => InvokableFactory::class,
],
],
'view_manager' => [
'template_path_stack' => [
'Users' => __DIR__ . '/../view',
],
],
];

/module/Users/src/Module.php

<?php
/**
* @link      http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license   http://framework.zend.com/license/new-bsd New BSD License
*/

namespace Users;

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

/config/application.config.php

<?php
/**
* If you need an environment-specific system or application configuration,
* there is an example in the documentation
* @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-system-configuration
* @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-application-configuration
*/
return [
// Retrieve list of modules used in this application.
'modules' => require __DIR__ . '/modules.config.php',

// These are various options for the listeners attached to the ModuleManager
'module_listener_options' => [
// This should be an array of paths in which modules reside.
// If a string key is provided, the listener will consider that a module
// namespace, the value of that key the specific path to that module's
// Module class.
'module_paths' => [
'./module',
'./vendor',
],

// An array of paths from which to glob configuration files after
// modules are loaded. These effectively override configuration
// provided by modules themselves. Paths may use GLOB_BRACE notation.
'config_glob_paths' => [
realpath(__DIR__) . '/autoload/{{,*.}global,{,*.}local}.php',
],

// Whether or not to enable a configuration cache.
// If enabled, the merged configuration will be cached and used in
// subsequent requests.
'config_cache_enabled' => true,

// The key used to create the configuration cache file name.
'config_cache_key' => 'application.config.cache',

// Whether or not to enable a module class map cache.
// If enabled, creates a module class map cache which will be used
// by in future requests, to reduce the autoloading process.
'module_map_cache_enabled' => true,

// The key used to create the class map cache file name.
'module_map_cache_key' => 'application.module.cache',

// The path in which to cache merged configuration.
'cache_dir' => 'data/cache/',

// Whether or not to enable modules dependency checking.
// Enabled by default, prevents usage of modules that depend on other modules
// that weren't loaded.
// 'check_dependencies' => true,
],

// Used to create an own service manager. May contain one or more child arrays.
// 'service_listener_options' => [
//     [
//         'service_manager' => $stringServiceManagerName,
//         'config_key'      => $stringConfigKey,
//         'interface'       => $stringOptionalInterface,
//         'method'          => $stringRequiredMethodName,
//     ],
// ],

// Initial configuration with which to seed the ServiceManager.
// Should be compatible with Zend\ServiceManager\Config.
// 'service_manager' => [],
];

/config/modules.config.php

<?php
/**
* @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license   http://framework.zend.com/license/new-bsd New BSD License
*/

/**
* List of enabled modules for this application.
*
* This should be an array of module namespaces used in the application.
*/
return [
'Zend\ServiceManager\Di',
'Zend\Session',
'Zend\Mvc\Plugin\Prg',
'Zend\Mvc\Plugin\Identity',
'Zend\Mvc\Plugin\FlashMessenger',
'Zend\Mvc\Plugin\FilePrg',
'Zend\Mvc\I18n',
'Zend\Log',
'Zend\Form',
'Zend\Db',
'Zend\Cache',
'ZendDeveloperTools',
'Zend\Router',
'Zend\Validator',
'Application',
'Users',
];

/composer.json

{
"name": "zendframework/skeleton-application",
"description": "Skeleton Application for Zend Framework zend-mvc applications",
"type": "project",
"license": "BSD-3-Clause",
"keywords": [
"framework",
"mvc",
"zf"],
"homepage": "http://framework.zend.com/",
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
"php": "^5.6 || ^7.0",
"zendframework/zend-component-installer": "^1.0 || ^0.3 || ^1.0.0-dev@dev",
"zendframework/zend-mvc": "^3.0.1",
"zfcampus/zf-development-mode": "^3.0",
"zendframework/zend-cache": "^2.7.1",
"zendframework/zend-db": "^2.8.1",
"zendframework/zend-mvc-form": "^1.0",
"zendframework/zend-json": "^3.0",
"zendframework/zend-log": "^2.9",
"zendframework/zend-mvc-i18n": "^1.0",
"zendframework/zend-mvc-plugins": "^1.0.1",
"zendframework/zend-psr7bridge": "^0.2.2",
"zendframework/zend-session": "^2.7.1",
"zendframework/zend-servicemanager-di": "^1.0"},
"autoload": {
"psr-4": {
"Application\\": "module/Application/src/",
"Users\\": "module/Users/src/"}
},
"autoload-dev": {
"psr-4": {
"ApplicationTest\\": "module/Application/test/"}
},
"extra": [],
"scripts": {
"cs-check": "phpcs",
"cs-fix": "phpcbf",
"development-disable": "zf-development-mode disable",
"development-enable": "zf-development-mode enable",
"development-status": "zf-development-mode status",
"post-create-project-cmd": [
"@development-enable"],
"serve": "php -S 0.0.0.0:8080 -t public/ public/index.php",
"test": "phpunit"},
"require-dev": {
"zendframework/zend-developer-tools": "^1.1.0",
"zendframework/zend-test": "^3.0.1"}
}

Обновление вопроса

Вот скриншот папок и содержание /module/Users/src/Controller/IndexController.php:

& Quot; / модуль / Пользователи / SRC & Quot; и & quot; / module / Users / view & quot; папки

/module/Users/src/Controller/IndexController.php

<?php
/**
* @link      http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license   http://framework.zend.com/license/new-bsd New BSD License
*/

namespace Users\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class IndexController extends AbstractActionController
{
public function indexAction()
{
return [];
}
}

Обновление вопроса 2 — добавлен еще один файл

liga.vconf

 <VirtualHost *:80>
ServerName liga.localhost
DocumentRoot /users/cassiomc/sites/sistemas/liga/public
SetEnv APPLICATION_ENV "development"<Directory /users/cassiomc/sites/sistemas/liga/public>
DirectoryIndex index.php
AllowOverride All
Require all granted
</Directory>
</VirtualHost>

Обновление вопроса

Вот скриншот экрана 404, который я получаю, когда пытаюсь получить доступ к Users модуль по ссылке liga.localhost/users,

404 экран при попытке доступа к модулю пользователей

Проблема решена — добавлены файлы для сравнения со старыми, а также файл «index.phtml» нового модуля «Пользователи»

/module/Users/config/module.config.php

<?php
namespace Users;

use Zend\ServiceManager\Factory\InvokableFactory;
use Zend\Router\Http\Segment;

return [
'controllers' => [
'factories' => [
Controller\IndexController::class => InvokableFactory::class,
],
],
'router' => [
'routes' => [
'users' => [
'type'    => Segment::class,
'options' => [
'route'    => '/users[/:action]',
'defaults' => [
'controller' => Controller\IndexController::class,
'action'     => 'index',
],
],
],
],
],
'view_manager' => [
'display_not_found_reason' => true,
'display_exceptions'       => true,
'doctype'                  => 'HTML5',
'not_found_template'       => 'error/404',
'exception_template'       => 'error/index',
'template_map' => [
'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
'users/index/index' => __DIR__ . '/../view/users/index/index.phtml',
'error/404'               => __DIR__ . '/../view/error/404.phtml',
'error/index'             => __DIR__ . '/../view/error/index.phtml',
],
'template_path_stack' => [
__DIR__ . '/../view',
],
],
];

/module/Users/src/Module.php

<?php
/**
* @link      http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license   http://framework.zend.com/license/new-bsd New BSD License
*/

namespace Users;

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

/config/application.config.php

<?php
/**
* If you need an environment-specific system or application configuration,
* there is an example in the documentation
* @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-system-configuration
* @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-application-configuration
*/
return [
// Retrieve list of modules used in this application.
'modules' => require __DIR__ . '/modules.config.php',

// These are various options for the listeners attached to the ModuleManager
'module_listener_options' => [
// This should be an array of paths in which modules reside.
// If a string key is provided, the listener will consider that a module
// namespace, the value of that key the specific path to that module's
// Module class.
'module_paths' => [
'./module',
'./vendor',
],

// An array of paths from which to glob configuration files after
// modules are loaded. These effectively override configuration
// provided by modules themselves. Paths may use GLOB_BRACE notation.
'config_glob_paths' => [
realpath(__DIR__) . '/autoload/{{,*.}global,{,*.}local}.php',
],

// Whether or not to enable a configuration cache.
// If enabled, the merged configuration will be cached and used in
// subsequent requests.
'config_cache_enabled' => false,

// The key used to create the configuration cache file name.
'config_cache_key' => 'application.config.cache',

// Whether or not to enable a module class map cache.
// If enabled, creates a module class map cache which will be used
// by in future requests, to reduce the autoloading process.
'module_map_cache_enabled' => false,

// The key used to create the class map cache file name.
'module_map_cache_key' => 'application.module.cache',

// The path in which to cache merged configuration.
'cache_dir' => 'data/cache/',

// Whether or not to enable modules dependency checking.
// Enabled by default, prevents usage of modules that depend on other modules
// that weren't loaded.
// 'check_dependencies' => true,
],

// Used to create an own service manager. May contain one or more child arrays.
// 'service_listener_options' => [
//     [
//         'service_manager' => $stringServiceManagerName,
//         'config_key'      => $stringConfigKey,
//         'interface'       => $stringOptionalInterface,
//         'method'          => $stringRequiredMethodName,
//     ],
// ],

// Initial configuration with which to seed the ServiceManager.
// Should be compatible with Zend\ServiceManager\Config.
// 'service_manager' => [],
];

/config/modules.config.php

<?php
/**
* @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license   http://framework.zend.com/license/new-bsd New BSD License
*/

/**
* List of enabled modules for this application.
*
* This should be an array of module namespaces used in the application.
*/
return [
'Zend\Router',
'Zend\Validator',
'Application',
'Users'
];

/composer.json

{
"name": "zendframework/skeleton-application",
"description": "Skeleton Application for Zend Framework zend-mvc applications",
"type": "project",
"license": "BSD-3-Clause",
"keywords": [
"framework",
"mvc",
"zf"],
"homepage": "http://framework.zend.com/",
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
"php": "^5.6 || ^7.0",
"zendframework/zend-component-installer": "^1.0 || ^0.3 || ^1.0.0-dev@dev",
"zendframework/zend-mvc": "^3.0.1",
"zfcampus/zf-development-mode": "^3.0"},
"autoload": {
"psr-4": {
"Application\\": "module/Application/src/",
"Users\\": "module/Users/src/"}
},
"autoload-dev": {
"psr-4": {
"ApplicationTest\\": "module/Application/test/"}
},
"extra": [],
"scripts": {
"cs-check": "phpcs",
"cs-fix": "phpcbf",
"development-disable": "zf-development-mode disable",
"development-enable": "zf-development-mode enable",
"development-status": "zf-development-mode status",
"post-create-project-cmd": [
"@development-enable"],
"serve": "php -S 0.0.0.0:8080 -t public/ public/index.php",
"test": "phpunit"}
}

Вот снимок экрана с папками и содержимым /module/Users/src/Controller/IndexController.php теперь кода работает:

Дерево каталогов

/module/Users/src/Controller/IndexController.php

<?php
/**
* @link      http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license   http://framework.zend.com/license/new-bsd New BSD License
*/

namespace Users\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class IndexController extends AbstractActionController
{
public function indexAction()
{
return [];
}
}

liga.vconf

 <VirtualHost *:80>
ServerName liga.localhost
DocumentRoot /users/cassiomc/sites/sistemas/liga/public
SetEnv APPLICATION_ENV "development"<Directory /users/cassiomc/sites/sistemas/liga/public>
DirectoryIndex index.php
AllowOverride All
Require all granted
</Directory>
</VirtualHost>

/module/Users/view/users/index/index.phtml

<strong>Module:</strong>        ZendSkeletonModule &raquo;
<strong>Controller:</strong>    Skeleton &raquo;
<strong>Action:</strong>        index

2

Решение

Если вы установили скелетное приложение с composer и всеми зависимостями по умолчанию, попробуйте следующее: Добавьте это в composer.json

"autoload": {
"psr-4": {
"Application\\": "module/Application/src/",
"NewModule\\": "module/NewModule/src/"}
},

и запустите следующее в командной строке

composer dump-autoload

У меня были те же проблемы, что и у вас, но после выполнения этих шагов модуль работает.

Вот шаг за шагом создания нового модуля
https://docs.zendframework.com/tutorials/getting-started/modules/

3

Другие решения

У меня такая же проблема. Проверьте папку data / cache, я удалил * .php файлы и мой модуль был найден приложением

2

Кажется, что ваш composer.json, /config/modules.config.php, /config/application.config.php, /module/Users/config/module.config.php, /module/Users/src/Module.php файлы правильные.

Убедитесь, что имена контроллера и действия согласованы между module/Users/config/module.config.php, module/Users/src/Controller/IndexController.php а также module/view/users/ дорожка

модуль / Users / SRC / Controller / IndexController.php

<?php
namespace Users\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class IndexController extends AbstractActionController
{
public function indexAction()
{
return [];
}
}

модуль / пользователей / индекс / index.phtml

<strong>Module:</strong>        UserModule &raquo;
<strong>Controller:</strong>    Index &raquo;
<strong>Action:</strong>        index

Другие попробовать

Если вы все сделали нормально, это может быть кеш. Попробуйте отключить его, включив режим разработки с помощью следующей команды: composer development-enable,

Это будет копировать config/development.config.php.dist в config/development.config.php и изменит параметр кэширования в module_listener_options массив.

Затем запустите сервер php с composer serve, Это должно работать (я сделал всю установку, как вы сделали, и это работает для меня). Если нет, у меня нет другой идеи …

0

Ваш Module.php должен выглядеть так:

<?php
/**
* @link      http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license   http://framework.zend.com/license/new-bsd New BSD License
*/

namespace Users;

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

Удалите «../» внутри возврата.

0
По вопросам рекламы [email protected]