0

I have a /files controller that will have two actions: upload and download

it's defined as follows:

'files' => array(
    'type' => 'Segment',
    'options' => array(
        'route' => '/files[/:action]',
        'defaults' => array(
            'controller' => 'Application\Controller\Files',
            'action' => 'index',
        ),
    ),
),

I want the download action to be accessed like /files/download/1?authString=asdf. 1 in this case is a fileId.

I understand I can just change the route to /files[/action[/:fileId]] to set up the route, correct me if I'm wrong, but then how do I access the fileId inside the downloadAction? And is there anything else I need to change about the route definition to make it work??

Bogdan
  • 1,869
  • 6
  • 24
  • 53

1 Answers1

2

I can just change the route to /files[/action[/:fileId]] to set up the route, correct me if I'm wrong

You're not wrong, that would be a valid route.

is there anything else I need to change about the route definition?

If you add the fileId as a optional route param then you will need to do some manual checking within the downloadAction() to ensure it is set.

Another solution would be to separate the routes into children, this ensures that unless you have the correct parameters on each route, it would not be matched.

'files' => array(
    'type' => 'Segment',
    'options' => array(
        'route' => '/files',
        'defaults' => array(
            'controller' => 'Application\Controller\Files',
            'action' => 'index',
        ),
    ),
    'may_terminate' => true,
    'child_routes' => array(

        'download' => array(
            'type' => 'Segment',
            'options' => array(
                'route' => '/download/:fileId',
                'defaults' => array(
                    'action' => 'download',
                ),
                'constraints' => array(
                    'fileId' => '[a-zA-Z0-9]+',
                ),
            ),
        ),

        'upload' => array(
            'type' => 'Literal',
            'options' => array(
                'route' => '/upload',
                'defaults' => array(
                    'action' => 'upload',
                ),
            ),
        ),

    ),
),

how do I access the fileId inside the downloadAction

The easiest way would be to use the Zend\Mvc\Controller\Plugin\Params controller plugin to fetch the parameter from the route).

// FilesController::downloadAction()
$fileId = $this->params('fileId');

Or specifically from the route

// FilesController::downloadAction()
$fileId = $this->params()->fromRoute('fileId');
Community
  • 1
  • 1
AlexP
  • 9,906
  • 1
  • 24
  • 43