We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Fullcontrol routing and rendering view

I'm pretty new with php frameworks, my only experience was Laravel, and though it's enjoyable, laravel isn't what I really want. After some search, I found out about Yaf and Phalcon which is really close to what I had in mind, a simple MVC architecture with speed.

Yaf document isn't that good, so I decided to stick with Phalcon. The INVO tutorial is good enough, but the thing is that, because my lacking of experience with php and all, I couldn't find the way to disable auto routing (controller/action/params) and instead map the route manually (to get the full control with the URI).

The other thing, I'd like to have full control with what views I would like to render (not the default controller = view convention), because sometime I would like to have a dynamic sidebar defending on the content of the site ( I know this could be achieve by using library, but I'd like to put any html in views (like it does in Laravel) to separate the logic and view to make it more maintainable.

Thanks for help.



32.5k
Accepted
answer
edited Mar '14

https://docs.phalcon.io/en/latest/reference/routing.html#default-behavior

// Create the router without default routes
$router = new \Phalcon\Mvc\Router(false);
// then use any patter you want
$router->add(
    "/posts/([0-9]{4})/([0-9]{2})/([a-z\-]+)",
    array(
        "controller" => "posts",
        "action"     => "show",
        "year"       => 1,
        "month"      => 2,
        "title"      => 4
    )
);

You can use https://docs.phalcon.io/en/1.0.0/api/index.html to find out all the methods you can use. There is a methods to change or to disable any of the layers: https://docs.phalcon.io/en/1.0.0/api/Phalcon_Mvc_View.html They can be used directly inside the controller or action, so you can build the view dynamically.

class IndexController extends Phalcon\Mvc\Controller
{
    public function indexAction()
    {
        // use /views/sign/in.phtml instead of /views/index/index.phtml as action layer
        $this->view->pick("sign/in");
        // don't use /views/layouts/index.phtml
        $this->view->disableLevel(View::LEVEL_LAYOUT);
    }
}

You can use partials to build view from smaller parts, with needed conditions as well:

<!DOCTYPE html>
<html>
    <head>
        <title>Blog's title</title>
    </head>
    <body>
        <header>
<?php if ($this->session->has('auth')) $this->partial("additional/user-authed-panel") ?>
        </header>
    </body>
</html>