Nano Hash - криптовалюты, майнинг, программирование

Zend Framework 2 Динамическая маршрутизация

Сейчас я пробую себя на Zend Framework 2 и у меня есть некоторые проблемы с маршрутизацией. У меня такая навигация:

Home
Current
    News
    Schedule
Club
    History
    Management
    Referee
    Restaurant
Team
    First
        Table
        Squad
    Second
        Table
        Squad
    Old
        Table
        Squad
    Djunior
        Table
        Squad
    Efjunior
        Table
        Squad
    National
        Table
        Squad
    Utility
        Table
        Squad
Sponsor
About
    Approach
    Contact
    Disclaimer
    Imprint

Мой module.config.php выглядит так:

return array(
    'router' => array(
        'routes' => array(
            //Literal-Route: Home
            //Controller: IndexController
            //View: index/index.phtml
            'home' => array(
                'type' => 'Zend\Mvc\Router\Http\Literal',
                'options' => array(
                    'route'    => '/',
                    'defaults' => array(
                        'controller' => 'Football\Controller\Index',
                        'action'     => 'index',
                    ),
                ),
            ),
            //Segment-Route: football
            'football' => array(
                'type'    => 'segment',
                'options' => array(
                    'route'    => '[/:controller[/:action]]',
                    'constraints' => array(
                        'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        '__NAMESPACE__' => 'Football\Controller',
                        'controller' => 'index',
                        'action'     => 'index',
                    ),
                ),
            ),
            'subteam' => array(
                'type'    => 'segment',
                'options' => array(
                    'route'    => '[/:controller[[/first]/:action]]',
                    'constraints' => array(
                        'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                    ),
                    'defaults' => array(
                        '__NAMESPACE__' => 'Football\Controller',
                        'controller' => 'index',
                        'action'     => 'index',
                    ),
                ),  
            ),
        ),
    ),
    'controllers' => array(
        'invokables' => array(
            'Football\Controller\Index' => 'Football\Controller\IndexController',
            'Football\Controller\Current' => 'Football\Controller\CurrentController',
            'Football\Controller\About' => 'Football\Controller\AboutController',
            'Football\Controller\Sponsor' => 'Football\Controller\SponsorController',
            'Football\Controller\Club' => 'Football\Controller\ClubController',
            'Football\Controller\Team' => 'Football\Controller\TeamController',
        ),
    ),
    'service_manager' => array(
        'factories' => array(
            'navigation' => 'Zend\Navigation\Service\DefaultNavigationFactory',
            'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
        ),
    ),
    'translator' => array(
        'locale' => 'en_US',
        'translation_file_patterns' => array(
            array(
                'type'     => 'gettext',
                'base_dir' => __DIR__ . '/../language',
                'pattern'  => '%s.mo',
            ),
        ),
    ),
    'navigation' => array(
        'default' => array(
            //localhost
            array(
                'label' => 'Home',
                'route' => 'home',
            ),
            //localhost/current
            'current' => array(
                'type'       => 'mvc',
                'order'      => '100',
                'label'      => 'Aktuelles',
                'route'      => 'football',
                'controller' => 'current',
                'action'     => 'index',
                'pages' => array(
                    //localhost/current/news
                    'news' => array(
                        'type'       => 'mvc',
                        'order'      => '100',
                        'label'      => 'Nachrichten',
                        'route'      => 'football',
                        'controller' => 'current',
                        'action'     => 'news',
                    ),
                    //localhost/current/schedule
                    'schedule' => array(
                        'type'       => 'mvc',
                        'order'      => '200',
                        'label'      => 'Trainingszeiten',
                        'route'      => 'football',
                        'controller' => 'current',
                        'action'     => 'schedule',
                    ),
                ),
            ),
            //localhost/club
            'club' => array(
                'type'       => 'mvc',
                'order'      => '200',
                'label'      => 'Verein',
                'route'      => 'football',
                'controller' => 'club',
                'action'     => 'index',
                'pages' => array(
                //localhost/club/history
                    'history' => array(
                        'type'       => 'mvc',
                        'order'      => '100',
                        'label'      => 'Geschichte',
                        'route'      => 'football',
                        'controller' => 'club',
                        'action'     => 'history',
                    ),
                    //localhost/club/management
                    'management' => array(
                        'type'       => 'mvc',
                        'order'      => '200',
                        'label'      => 'Vorstand',
                        'route'      => 'football',
                        'controller' => 'club',
                        'action'     => 'management',
                    ),
                    //localhost/club/referee
                    'referee' => array(
                        'type'       => 'mvc',
                        'order'      => '300',
                        'label'      => 'Schiedsrichter',
                        'route'      => 'football',
                        'controller' => 'club',
                        'action'     => 'referee',
                    ),
                    //localhost/club/restaurant
                    'restaurant' => array(
                        'type'       => 'mvc',
                        'order'      => '400',
                        'label'      => 'Gaststätte',
                        'route'      => 'football',
                        'controller' => 'club',
                        'action'     => 'restaurant',
                    ),
                ),
            ),
            //localhost/team
            'team' => array(
                'type'       => 'mvc',
                'order'      => '300',
                'label'      => 'Mannschaften',
                'route'      => 'football',
                'controller' => 'team',
                'action'     => 'index',
                'pages' => array(
                //localhost/team/first
                    'first' => array(
                        'type'       => 'mvc',
                        'order'      => '100',
                        'label'      => '1. Herren',
                        'route'      => 'football',
                        'controller' => 'team',
                        'action'     => 'first',
                        'pages' => array(
                            //localhost/team/first/table
                            'table' => array(
                                'type'       => 'mvc',
                                'order'      => '100',
                                'label'      => 'Tabelle',
                                'route'      => 'subteam',
                                'controller' => 'team',
                                'action'     => 'table',
                            ),
                            //localhost/team/first/squad
                            'squad' => array(
                                'type'       => 'mvc',
                                'order'      => '200',
                                'label'      => 'Mannschaftskader',
                                'route'      => 'subteam',
                                'controller' => 'team',
                                'action'     => 'squad',
                            ),
                        ),
                    ),
                    //localhost/team/second
                    'second' => array(
                        'type'       => 'mvc',
                        'order'      => '200',
                        'label'      => '2. Herren',
                        'route'      => 'football',
                        'controller' => 'team',
                        'action'     => 'second',
                        'pages' => array(
                            //localhost/team/second/table
                            'table' => array(
                                'type'       => 'mvc',
                                'order'      => '100',
                                'label'      => 'Tabelle',
                                'route'      => 'subteam',
                                'controller' => 'team',
                                'action'     => 'table',
                            ),
                            //localhost/team/second/squad
                            'squad' => array(
                                'type'       => 'mvc',
                                'order'      => '200',
                                'label'      => 'Mannschaftskader',
                                'route'      => 'subteam',
                                'controller' => 'team',
                                'action'     => 'squad',
                            ),
                        ),
                    ),
                    //localhost/team/old
                    'old' => array(
                        'type'       => 'mvc',
                        'order'      => '300',
                        'label'      => 'Alte Herren',
                        'route'      => 'football',
                        'controller' => 'team',
                        'action'     => 'old',
                        'pages' => array(
                            //localhost/team/old/table
                            'table' => array(
                                'type'       => 'mvc',
                                'order'      => '100',
                                'label'      => 'Tabelle',
                                'route'      => 'subteam',
                                'controller' => 'team',
                                'action'     => 'table',
                            ),
                            //localhost/team/old/squad
                            'squad' => array(
                                'type'       => 'mvc',
                                'order'      => '200',
                                'label'      => 'Mannschaftskader',
                                'route'      => 'subteam',
                                'controller' => 'team',
                                'action'     => 'squad',
                            ),
                        ),
                    ),
                    //localhost/team/djunior
                    'djunior' => array(
                        'type'       => 'mvc',
                        'order'      => '400',
                        'label'      => 'D-Junioren',
                        'route'      => 'football',
                        'controller' => 'team',
                        'action'     => 'djunior',
                        'pages' => array(
                            //localhost/team/djunior/table
                            'table' => array(
                                'type'       => 'mvc',
                                'order'      => '100',
                                'label'      => 'Tabelle',
                                'route'      => 'subteam',
                                'controller' => 'team',
                                'action'     => 'table',
                            ),
                            //localhost/team/djunior/squad
                            'squad' => array(
                                'type'       => 'mvc',
                                'order'      => '200',
                                'label'      => 'Mannschaftskader',
                                'route'      => 'subteam',
                                'controller' => 'team',
                                'action'     => 'squad',
                            ),
                        ),
                    ),
                    //localhost/team/efjunior
                    'efjunior' => array(
                        'type'       => 'mvc',
                        'order'      => '500',
                        'label'      => 'E/F-Junioren',
                        'route'      => 'football',
                        'controller' => 'team',
                        'action'     => 'efjunior',
                        'pages' => array(
                            //localhost/team/efjunior/table
                            'table' => array(
                                'type'       => 'mvc',
                                'order'      => '100',
                                'label'      => 'Tabelle',
                                'route'      => 'subteam',
                                'controller' => 'team',
                                'action'     => 'table',
                            ),
                            //localhost/team/efjunior/squad
                            'squad' => array(
                                'type'       => 'mvc',
                                'order'      => '200',
                                'label'      => 'Mannschaftskader',
                                'route'      => 'subteam',
                                'controller' => 'team',
                                'action'     => 'squad',
                            ),
                        ),
                    ),
                    //localhost/team/national/
                    'national' => array(
                        'type'       => 'mvc',
                        'order'      => '600',
                        'label'      => 'Volkssport',
                        'route'      => 'football',
                        'controller' => 'team',
                        'action'     => 'national',
                        'pages' => array(
                            //localhost/team/national/table
                            'table' => array(
                                'type'       => 'mvc',
                                'order'      => '100',
                                'label'      => 'Tabelle',
                                'route'      => 'subteam',
                                'controller' => 'team',
                                'action'     => 'table',
                            ),
                            //localhost/team/national/squad
                            'squad' => array(
                                'type'       => 'mvc',
                                'order'      => '200',
                                'label'      => 'Mannschaftskader',
                                'route'      => 'subteam',
                                'controller' => 'team',
                                'action'     => 'squad',
                            ),
                        ),
                    ),
                    //localhost/team/utility/
                    'utility' => array(
                        'type'       => 'mvc',
                        'order'      => '700',
                        'label'      => 'Stadtwerke',
                        'route'      => 'football',
                        'controller' => 'team',
                        'action'     => 'utility',
                        'pages' => array(
                            //localhost/team/utility/table
                            'table' => array(
                                'type'       => 'mvc',
                                'order'      => '100',
                                'label'      => 'Tabelle',
                                'route'      => 'subteam',
                                'controller' => 'team',
                                'action'     => 'table',
                            ),
                            //localhost/team/utility/squad
                            'squad' => array(
                                'type'       => 'mvc',
                                'order'      => '200',
                                'label'      => 'Mannschaftskader',
                                'route'      => 'subteam',
                                'controller' => 'team',
                                'action'     => 'squad',
                            ),
                        ),
                    ),
                ),
            ),
            //localhost/sponsor
            'sponsor' => array(
                'type'       => 'mvc',
                'order'      => '400',
                'label'      => 'Sponsoren',
                'route'      => 'football',
                'controller' => 'sponsor',
                'action'     => 'index',
            ),
            //localhost/about
            'about' => array(
                'type'       => 'mvc',
                'order'      => '500',
                'label'      => 'Über uns',
                'route'      => 'football',
                'controller' => 'about',
                'action'     => 'index',
                'pages' => array(
                    //localhost/about/approach
                    'approach' => array(
                        'type'       => 'mvc',
                        'order'      => '100',
                        'label'      => 'Anfahrt',
                        'route'      => 'football',
                        'controller' => 'about',
                        'action'     => 'approach',
                    ),
                    //localhost/about/contact
                    'contact' => array(
                        'type'       => 'mvc',
                        'order'      => '200',
                        'label'      => 'Kontakt',
                        'route'      => 'football',
                        'controller' => 'about',
                        'action'     => 'contact',
                    ),
                    //localhost/about/disclaimer
                    'disclaimer' => array(
                        'type'       => 'mvc',
                        'order'      => '300',
                        'label'      => 'Disclaimer',
                        'route'      => 'football',
                        'controller' => 'about',
                        'action'     => 'disclaimer',
                    ),
                    //localhost/about/imprint
                    'imprint' => array(
                        'type'       => 'mvc',
                        'order'      => '400',
                        'label'      => 'Impressum',
                        'route'      => 'football',
                        'controller' => 'about',
                        'action'     => 'imprint',
                    ),
                ),
            ),
        ),
    ),                                              
    'view_manager' => array(
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => array(
            'layout/layout'        => __DIR__ . '/../view/layout/layout.phtml',
            'layout/header'        => __DIR__ . '/../view/layout/header.phtml',
            'layout/sidebar'        => __DIR__ . '/../view/layout/sidebar.phtml',
            'layout/footer'        => __DIR__ . '/../view/layout/footer.phtml',
            'football/index/index' => __DIR__ . '/../view/football/index/index.phtml',
            'error/404'            => __DIR__ . '/../view/error/404.phtml',
            'error/index'          => __DIR__ . '/../view/error/index.phtml',
        ),
        'template_path_stack' => array(
            __DIR__ . '/../view',
        ),
    ),
);

Я думаю, что моя проблема теперь в маршруте подгруппы, потому что он статичен, поэтому, когда я нажимаю, например. для Team->Second->Table маршрут будет "Team->First->Table". Неважно, какую команду я нажимаю, эта «первая» часть всегда там, и я не знаю, как я делаю это динамически. Надеюсь, это понятно для вас, ребята, и кто-то может ясно объяснить мне, как сделать эти командные маршруты динамическими. :)

Редактировать: я обновил module.config.php, теперь вы видите весь файл.

Оконтроллер.php

namespace Football\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class AboutController extends AbstractActionController
{
 public function indexAction()
{
     return new ViewModel();
 }

public function contactAction()
{
    return new ViewModel();
 }

public function approachAction()
{
     return new ViewModel();
 }

 public function disclaimerAction()
{
     return new ViewModel();
 }

public function imprintAction()
 {
     return new ViewModel();
 }

ClubController.php

namespace Football\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class ClubController extends AbstractActionController
{
public function indexAction()
{
    return new ViewModel();
}

public function historyAction()
{
    return new ViewModel();
 }

public function managementAction()
 {
    return new ViewModel();
 }

 public function refereeAction()
 {
    return new ViewModel();
 }

public function restaurantAction()
{
    return new ViewModel();
}

ТекущийКонтроллер.php

namespace Football\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class CurrentController extends AbstractActionController
{
public function indexAction()
{
    return new ViewModel();
}

public function newsAction()
{
    return new ViewModel();
}

public function scheduleAction()
{
    return new ViewModel();
}

Индексконтроллер.php

namespace Football\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
public function indexAction()
{
    return new ViewModel();
}

public function clubAction()
{
    return new ViewModel();
}

public function contactAction()
{
    return new ViewModel();
}

public function currentAction()
{
    return new ViewModel();
}

public function teamAction()
{
    return new ViewModel();
}

public function sponsorAction()
{
    return new ViewModel();
}

public function approachAction()
{
    return new ViewModel();
}

public function imprintAction()
{
    return new ViewModel();
}

SponsorController.php

namespace Football\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class SponsorController extends AbstractActionController
{
public function indexAction()
{
    //DatenbankAdapter holen
    $db = $this->getServiceLocator()->get('db');

    return new ViewModel(array('db' => $db));
}

TeamController.php

namespace Football\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class TeamController extends AbstractActionController
{
public function indexAction()
{
    return new ViewModel();
}

public function firstAction()
{
    return new ViewModel();
}

public function tableAction()
{
    return new ViewModel();
}

public function squadAction()
{
    return new ViewModel();
}

public function secondAction()
{
    return new ViewModel();
}

public function oldAction()
{
    return new ViewModel();
}

public function djuniorAction()
{
    return new ViewModel();
}

public function efjuniorAction()
{
    return new ViewModel();
}

public function nationalAction()
{
    return new ViewModel();
}

public function utilityAction()
{
    return new ViewModel();
}

  • Ни у кого нет идеи/совета/решения моей проблемы? 24.02.2015
  • Мне немного трудно понять, что вы пытаетесь сделать. Не могли бы вы предоставить список ваших контроллеров с действиями и как они должны соответствовать предоставленной вами структуре навигации? Маршруты, которые у вас там есть, настолько универсальны, что трудно сказать, что-должно-составлять-где. 24.02.2015
  • Я добавил полный файл module.config.php и свои контроллеры, надеюсь, это то, что вам нужно. Может быть, я снова расскажу о проблеме: я пытаюсь достичь, например. эта ссылка дома-›команда-›второй-›стол, но когда я перейду на сайт, я получу дома-›команда-›первый-›стол. Таким образом, я получаю неправильный стол от неправильной команды. Я думаю, что проблема в подгруппе маршрута, но я не знаю, как ее решить. 24.02.2015
  • Хорошо, так лучше. Но как должны работать разделы table и squad? У вас есть только один из них в TeamController, но в навигации их несколько. Итак, /team/first/table/ и /team/second/table должны отправлять одно и то же действие, и вы бы их как-то различали? 24.02.2015
  • Да я думал, что эти ссылки будут вести все к одному действию и показывать таблицу нажатой команды с каким-то if-else, то же самое и для отряда. Должен ли я попробовать другой способ реализовать это или что вы думаете об этом? Другой вопрос для меня, как я могу решить эту /team/first/table/ и /team/second/table. 24.02.2015

Ответы:


1

Ваша основная проблема, я думаю, может быть решена как минимум двумя способами:

  • дочерние маршруты для действий table и squad
  • или добавьте третий необязательный параметр, который будет содержать значение table|squad, направьте его на действия для типов команд и добавьте туда условие. См. пример ниже

конфигурация:

// ...
'router' => array(
    'routes' => array(
        'home' => array(
            'type' => 'Literal',
            'may_terminate' => true,
            'options' => array(
                'route'    => '/',
                'defaults' => array(
                    'controller' => 'Football\Controller\Index',
                    'action'     => 'index',
                ),
            ),
        ),
        'football' => array(
            'type'    => 'segment',
            'may_terminate' => true,
            'options' => array(
                'route'    => '/:controller[/:action[/:extra]]',
                'constraints' => array(
                    'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                    'extra' => '(squad|table)',
                ),
                'defaults' => array(
                    'controller' => 'Football\Controller\Index',
                    'action'     => 'index',
                ),
            ),
        ),
    ),
),

Что касается навигации:

// ...
'pages' => array(
    'first' => array(
        'type'       => 'mvc',
        'order'      => '100',
        'label'      => '1. Herren',
        'route'      => 'football',
        'controller' => 'team',
        'action'     => 'first',
        'pages' => array(
            'table' => array(
                'type'       => 'mvc',
                'order'      => '100',
                'label'      => 'Tabelle',
                'route'      => 'football',
                'params' => array(
                    'extra' => 'table',
                ),
                'controller' => 'team',
                'action'     => 'table',
            ),
            'squad' => array(
                'type'       => 'mvc',
                'order'      => '200',
                'label'      => 'Mannschaftskader',
                'route'      => 'football',
                'params' => array(
                    'extra' => 'squad',
                ),
                'controller' => 'team',
                'action'     => 'squad',
            ),
        ),
    ),
24.02.2015
  • Спасибо за ответ, но, похоже, это не работает. Когда я хочу пойти на /team/first/table, я приземляюсь на /team/table/table. Я думаю, что что-то не так с моей маршрутизацией :/ 26.02.2015
  • У меня есть одна страница add.php, и эта страница используется как для добавления/редактирования с одним и тем же действием, так и для динамической настройки маршрутизации для этой страницы. 29.08.2018
  • Новые материалы

    Кластеризация: более глубокий взгляд
    Кластеризация — это метод обучения без учителя, в котором мы пытаемся найти группы в наборе данных на основе некоторых известных или неизвестных свойств, которые могут существовать. Независимо от..

    Как написать эффективное резюме
    Предложения по дизайну и макету, чтобы представить себя профессионально Вам не позвонили на собеседование после того, как вы несколько раз подали заявку на работу своей мечты? У вас может..

    Частный метод Python: улучшение инкапсуляции и безопасности
    Введение Python — универсальный и мощный язык программирования, известный своей простотой и удобством использования. Одной из ключевых особенностей, отличающих Python от других языков, является..

    Как я автоматизирую тестирование с помощью Jest
    Шутка для победы, когда дело касается автоматизации тестирования Одной очень важной частью разработки программного обеспечения является автоматизация тестирования, поскольку она создает..

    Работа с векторными символическими архитектурами, часть 4 (искусственный интеллект)
    Hyperseed: неконтролируемое обучение с векторными символическими архитектурами (arXiv) Автор: Евгений Осипов , Сачин Кахавала , Диланта Хапутантри , Тимал Кемпития , Дасвин Де Сильва ,..

    Понимание расстояния Вассерштейна: мощная метрика в машинном обучении
    В обширной области машинного обучения часто возникает необходимость сравнивать и измерять различия между распределениями вероятностей. Традиционные метрики расстояния, такие как евклидово..

    Обеспечение масштабируемости LLM: облачный анализ с помощью AWS Fargate и Copilot
    В динамичной области искусственного интеллекта все большее распространение получают модели больших языков (LLM). Они жизненно важны для различных приложений, таких как интеллектуальные..