We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Router annotations optional param

Hi, I am trying to set an optional param in a method using annotations but it does not work.

Here is my code:

/**
 * Class MessagesController
 *
 * @RoutePrefix('/mail')
 */
class MessagesController extends \Phalcon\Mvc\Controller
{
    /**
     * @param $page
     *
     * @Get('/inbox[/]?(page:[0-9]*)')
     */
    public function inboxAction($page = 0)
    {
        // code ..
    }

It redirects me to index controller instead of messages controller



8.1k
@Get("/inbox/{page:([0-9]+)}")

In your logic of Get annotation you accept inbox/page and /inboxpage routes. Param not defined.

edited Apr '15

I need the parameter to be optional so when I call either /mail/inbox or /mail/inbox/1 the method indexAction should be dispatched

this expression works with the second case only

@Get("/inbox/{page:([0-9]+)}")


973
Accepted
answer

I found the solution by using the @Get twice

/**
     * @param $page
     *
     * @Get('/inbox')
     * @Get('/inbox/{page:[0-9]+}')
     */

Thank you



8.1k

You don't bother?

Just write

@Get("/inbox/{page:([0-9]+)?}")

and in controller (example)

public function indexAction($pagenum = null)
    {

        is_string($pagenum) ?: $pagenum = "page/1";
        $paginator = new \Phalcon\Paginator\Adapter\Model(array(
            "data" => Discussions::find(array(
                'order' => 'createdAt DESC',
            )),
            "limit" => 15,
            "page" => (int) substr($pagenum, 5),
        ));
        $discussions = $paginator->getPaginate();
        $this->view->setVars(['discussions' => $discussions]);
    }

Then "/inbox" and "/inbox/page/1" will be work.

http://php.net/manual/en/pcre.pattern.php

Sure, no :)

I test the code you write but the expression here is not wokring in case I do not provide a param value

@Get("/inbox/{page:([0-9]+)?}")

the router cannot find a match route



8.1k
curl -I http://forumphalcon.dev/
HTTP/1.1 200 OK
X-Powered-By: PHP/5.6.8
Content-type: text/html; charset=UTF-8
Date: Thu, 23 Apr 2015 11:24:09 GMT
Server: lighttpd/1.4.35
curl -I http://forumphalcon.dev/page/1
HTTP/1.1 200 OK
X-Powered-By: PHP/5.6.8
Content-type: text/html; charset=UTF-8
Date: Thu, 23 Apr 2015 11:24:05 GMT
Server: lighttpd/1.4.35
curl -I http://forumphalcon.dev/page/2
HTTP/1.1 200 OK
X-Powered-By: PHP/5.6.8
Content-type: text/html; charset=UTF-8
Date: Thu, 23 Apr 2015 11:26:13 GMT
Server: lighttpd/1.4.35

Your application or server has incorrect settings