0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ZendFramework2 でのルーティング設定名にスラッシュ(/)を使ってはいけない

Posted at

zf2で複数モジュールを使う際にあるモジュール設定(module.config.php)のルーティング設定名で以下のようにスラッシュを使っていました。

module.config.php
'router' => [
    'routes' => [
        '/api/test' => [
            'type'    => Segment::class,
            'options' => [
                'route'    => '/api/test[/:action]',
                'defaults' => [
                    'controller' => Controller\TestController::class,
                    'action'     => 'index',
                ],
            ],
        ],
    ],
],

ルーティング設定は動作していたのですが、あるControllerのリンク生成でPhpRenderer::url($name = null, array $params = array(), $options = array(), $reuseMatchedParams = false)を使ったらうまく動作しませんでした。
デバッグして確認したところurl()の第一引数からmodule.config.phpのルーティング設定名(/api/test)を検索するのだけど第一引数をexplode('/')してから検索していたので引っかからなかったようです。

Zend\Mvc\Router\Http\TreeRouteStack.php
public function assemble(array $params = array(), array $options = array())
{
    if (!isset($options['name'])) {
        throw new Exception\InvalidArgumentException('Missing "name" option');
    }

    $names = explode('/', $options['name'], 2);
    $route = $this->routes->get($names[0]);
    ・・・
}

ルーティング設定名にスラッシュを使えないことは分かったけど、モジュールによってコンテキストパスを分けたかったのでどんな命名規則にしようか悩んだところそれっぽい例があったのでハイフンでつなぐこととしました。

module.config.php
'router' => [
    'routes' => [
        'api-test' => [ // ★修正箇所
            'type'    => Segment::class,
            'options' => [
                'route'    => '/api/test[/:action]',
                'defaults' => [
                    'controller' => Controller\TestController::class,
                    'action'     => 'index',
                ],
            ],
        ],
    ],
],
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?