简体   繁体   中英

ZF2 Have all routes resolve to one controller and action

I'm trying to develop and single page app with AngularJS and ZF2. I'm having trouble with the routing. My idea is to have routes like /:controller/:action resolve to a single action. I've read the docs and tried the different routing types.

My idea is to have all /:controller/:action to resolve to App\\IndexController\\IndexAction so only the Angular init code is returned. After the initial page has loaded, Angular will send a secondary request to /template/:controller/:action to retrieve the template and /api/:controller/:action to gather to template's data. Below is an example of the Regex route I attempted to make work.

'app' => array(
    'type'    => 'Regex',
    'options' => array(
        'regex'    => '/(?[a-zA-Z][a-zA-Z0-9_-]*\/[a-zA-Z][a-zA-Z0-9_-]*)',
        'defaults' => array(
            'controller'    => 'App\Controller\IndexController',
            'action'        => 'index',
        ),
        'spec' => '/'
    ),
    'may_terminate' => true,
),

Why you just don't define 3 major routes of segment type. See the code below:

'all' => [
    'type'    => 'Segment',
    'options' => [
        'route'    => '/app/[:controller[/:action]]',
        'constraints' => [
            'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
            'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
        ],
        'defaults' => [
            'controller' => 'App\Controller\IndexController',
            'action' => 'index'
        ],
    ],
],

'template' => [
    'type'    => 'Segment',
    'options' => [
        'route'    => '/template/[:controller[/:action]]',
        'constraints' => [
            'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
            'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
        ],
        'defaults' => [],
    ],
],

'api' => [
    'type'    => 'Segment',
    'options' => [
        'route'    => '/api/[:controller[/:action]]',
        'constraints' => [
            'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
            'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
        ],
        'defaults' => [],
    ],
]

Just use a Segment route:

'app' => array(
    'type' => 'Segment',
    'options' => array(
        'route' => ':controller-fake/:action-fake',
        'defaults' => array(
            'controller' => 'App\Controller\Index',
            'action' => 'index',
        ),
    ),
),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM