Search code examples
phpphalconvoltphalcon-routing

Is it possible to dynamically change view name or create a view that does not exist yet in phalcon?


I would like to know how can i do this in phalcon. I have a web site build with phalcon. All is working great now i stumbled upon a problem, here is what i need.

When a user clicks on a post that was created by another user. It takes him to this post with pictures and all things he entered to DB. I would like that in browser the name of this view is not like www.website.com/posts/index but that it is like www.website.com/posts/Nameofthepost, and like that for each other postings on the website. So that all posts (really ads) show their name up in browser. I hope i wrote everything understandable.

Appreciate all suggestions


Solution

  • That has to do with routing doesn't it? I modified this from my own code, I used grouping, you don't have to. I didn't test this code.

    // routes.php
    
    $router = new \Phalcon\Mvc\Router();
    $router->setDefaultModule("__YOUR_MODULE__");
    $router->removeExtraSlashes(true);
    
    ... your other routes ...
    
    // posts group
    
    $posts = new \Phalcon\Mvc\Router\Group(array(
        'module' => '__YOUR_MODULE__',
        'controller' => 'posts',
        'action' => 'index'
    ));
    
    // All the routes start with /post
    $posts->setPrefix('/post');
    
    $posts->add('/{postName}/:params', array(
        'action' => 'index',
        'params' => 2
    ));
    
    // Maybe this will be enough for your needs, 
    // the one above has a catch all params, which
    // has to be manually parsed
    $posts->add('/{postName}', array(
        'action' => 'index',
    ));
    
    $posts->add('[/]*', array(
        'action' => 'index',
    ));
    $router->mount($posts);
    unset($posts);
    
    ... other routes ...
    
    return $router;
    

    On your controller, you can get the postName param this way:

    $this->dispatcher->getParam('permaPath');
    

    As shown in the phalcon routing documentation, you can use regex in your routing config, something like this?

    $posts->add('/{postName:[-0-6_A-Za-z]+}/:params', array(
        'action' => 'index',
        'params' => 2
    ));
    

    So, only -_, 0-9, A-Z, a-z allowed for postName. If the URL had a comma in there or something, then route doesn't match, 404 page not found.