Create a very simple named route in Zend Framework using its MVC

I just put together a very simple site using Zend Framework and its MVC. (Actually, I don't even use models at the moment, it's all just Controllers / Views for static information so far).

When I started to tinker with forms, I realized that in the examples for Zend_Form they use something like this, this sets the action of the form:

$form->setAction('/user/login')

      

which contains the url. I understand that Zend Framework has routes and that they can be called, but I cannot figure out how to create a simple route for a specific Controller / Action so that I can do something like this:

$form->setAction($named_route)
// or 
$form->setAction('named_route')

      

Hope my question is clear. I haven't been able to find any duplicate questions, but if you spot one and point it out, I won't mind.

Resource links are as good as examples, so don't waste your time if you know about a decent blog. Thanks!

0


a source to share


1 answer


Literature: http://framework.zend.com/manual/en/zend.controller.router.html#zend.controller.router.routes.standard - Look for "12.5.7.1. Zend_Controller_Router_Route" for a clearer explanation.

This is not the best way to do it, but I have a working example. I welcome corrections. Seeing Shorten Zend Framework route definitions , I agree that named routes should go in their own config (I'm using Django, and named views / urls are usually stripped), but here I'll just define routes in my Bootstrap.

So, in Bootstrap.php, inside the Bootstrap class, of course, I created a function that will automatically run, like this:

public function _initRoutes()
{
    $frontController = Zend_Controller_Front::getInstance();
    $route = new Zend_Controller_Router_Route(
        'login/', // The URL, after the baseUrl, with no params.
        array(
            'controller' => 'login', // The controller to point to.
            'action'     => 'index'  // The action to point to, in said Controller.
        )
    );
    $frontController->getRouter()->addRoute('loginpage', $route);
}

      

In the above example, the "login page" will be named "Named Route".

So, inside my LoginController (in the function that builds the form) instead of doing



$form->setAction('/blah/login')

      

I extract the URL of the named route and pass it like this:

$form_action_url = $this->view->Url(array(), 'loginpage', true);
// -- SNIP --
$form->setAction($form_action_url) // ...

      

It might be pointless and wrong, but it seems to be working at the moment. My reason for a named url where Zend Framework treats urls as / Controller / View (Action) / automatically is because I am anal about it. I've been using Django for a while where urls are predefined and I love it.

Zend Framework MVC url generated from window is good because.

Feel free to add notes and corrections to how this should work!

+1


a source







All Articles