Zend Custom Route if no match found - zend-framework

I have a ZF app with several modules as this: ( as usual )
root\
\application\
\default
\items
\me
\controllers
\views
The application uses the default routing like /module/controller/action;
What I want is this: if no match has been found for the default Zend Routing (no action / controller / module has been found ) then route to a desired path with the url endpoint spitted into parameters.
For example:
mydomain.lh/me -> will match the module me, controller index, action index ( as default )
mydomain.lh/my_category_name -> will match the module items, controller index, action index, params: category => my_category_name -> using the desired path route
no my_category_name module exists to match against
I have tried with this, into bootstrap.php:
public function _initRoutes ()
{
$router = $this->_front->getRouter(); // returns a rewrite router by default
$router->addRoute(
'cat-item',
new Zend_Controller_Router_Route('/:category',
array(
'module' => 'items',
'controller' => 'index',
'action' => 'index'))
);
}
Witch points to the correct location ( I know because I var_dump -ed the request url into the items/index/index action and the expected url and parameters were there, but if I do not do var_dump(something);exit; into the action, a blank page is served.
no output is made but also no error is generated, the request status is 200 - OK
Can anybody have a suggestion ?
Thank you!

Related

How to get the variables in routing in zend framework 1.12

I am new to routing in zf. I don't understand some terms in route
$route = new Zend_Controller_Router_Route(
'author/:username',
array(
'controller' => 'profile',
'action' => 'userinfo'
)
);
$router->addRoute('user', $route);
How do we get :username here? from where do we get this?
Username here is parameter pass by the user. So correct link using this route will be http://somepage.com/author/John. In your controller you can get this variable just like POST and GET variables - $this->getParam('author');
If you want to allow user use link without parameter (default parameter) you can add to array - 'author' => null (i usually use this in pagination)

Zend adding parameter to URL before generating view

The title might be misleading but I'm trying to do something very simple but cant figure it out.
Lets say I have a Question controller and show action and question id is the primary key with which I look up question details - so the URL looks like this
http://www.example.com/question/show/question_id/101
This works fine - So when the view is generated - the URL appears as shown above.
Now in the show action, what I want to do is, append the question title (which i get from database) to the URL - so when the view is generated - the URL shows up as
http://www.example.com/question/show/question_id/101/how-to-make-muffins
Its like on Stack overflow - if you take any question page - say
http://stackoverflow.com/questions/5451200/
and hit enter
The question title gets appended to the url as
http://stackoverflow.com/questions/5451200/make-seo-sensitive-url-avoid-id-zend-framework
Thanks a lot
You will have to add a custom route to your router, unless you can live with an url like:
www.example.com/question/show/question_id/101/{paramName}/how-to-make-muffins
You also, if you want to ensure that this parameter is always showing up, need to check if the parameter is set in the controller and issue a redirect if it is missing.
So, in your bootstrap file:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
public function _initRoutes ()
{
// Ensure that the FrontController has been bootstrapped:
$this->bootstrap('FrontController');
$fc = $this->getResource('FrontController');
/* #var $router Zend_Controller_Router_Rewrite */
$router = $fc->getRouter();
$router->addRoutes( array (
'question' => new Zend_Controller_Router_Route (
/* :controller and :action are special parameters, and corresponds to
* the controller and action that will be executed.
* We also say that we should have two additional parameters:
* :question_id and :title. Finally, we say that anything else in
* the url should be mapped by the standard {name}/{value}
*/
':controller/:action/:question_id/:title/*',
// This argument provides the default values for the route. We want
// to allow empty titles, so we set the default value to an empty
// string
array (
'controller' => 'question',
'action' => 'show',
'title' => ''
),
// This arguments contains the contraints for the route parameters.
// In this case, we say that question_id must consist of 1 or more
// digits and nothing else.
array (
'question_id' => '\d+'
)
)
));
}
}
Now that you have this route, you can use it in your views like so:
<?php echo $this->url(
array(
'question_id' => $this->question['id'],
'title' => $this->question['title']
),
'question'
);
// Will output something like: /question/show/123/my-question-title
?>
In your controller, you need to ensure that the title-parameter is set, or redirect to itself with the title set if not:
public function showAction ()
{
$question = $this->getQuestion($this->_getParam('question_id'));
if(!$this->_getParam('title', false)) {
$this->_helper->Redirector
->setCode(301) // Tell the client that this resource is permanently
// residing under the full URL
->gotoRouteAndExit(
array(
'question_id' => $question['id'],
'title' => $question['title']
)
);
}
[... Rest of your code ...]
}
This is done using a 301 redirect.
Fetch the question, filter out and/or replace URL-illegal characters, then construct the new URL. Pass it to the Redirector helper (in your controller: $this->_redirect($newURL);)

Zend router behaviour

I have some trouble with the router.
I have a custom route :
$router->addRoute('showTopic',
new Zend_Controller_Router_Route('/forum/topic/:topic',
array('module' => 'forum',
'controller' => 'topic',
'action' => 'show'),
array('topic' => '\d+')));
But when I try to access this url : localhost/forum/topic/16
I get this error :
Fatal error: Uncaught exception 'Zend_Controller_Router_Exception' with message 'topic is not specified'
But I don't want to put a default value for topic, because I also want the route /forum/topic to list all topics...
Secondly, I know that if I add a custom route, the default router is overridden, but I need to have some default routes too. The only way I have found is to set 'default' in the second parameter of the url view helper, like this
$this->url(array(
'module' => 'forum',
'controller' => 'topic',
'action' => 'add'
), 'default', true)
Is there a more elegant way instead of doing this for all url where I want to use the default behavior ?
You should have a default value for a topic and add the more general route (the one for forum/topic) after the more specific one. Route_Rewrite checks the routes beginning with the last one (it actually does an array_inverse).
The url helper delegates assembly urls to a route, its second paremeter being the name of the route to pull from the router. Since the default route is registered under the name of 'default', there is nothing really inelegant in using the name (it is not a magic string or a special case). If this really bugs you, you could write a custom helper (to be placed under "views/helpers"):
class Zend_View_Helper_DefaultUrl extends Zend_View_Helper_Abstract {
public function defaultUrl($params) {
return $this->view->url($params, 'default');
}
}
And use it in your view like defaultUrl(array('action'=>'test')) ?>.

Hostname and Custom routing in Zend Framework don't work together for me

I am building an application that uses hostname routing to detect subdomains like
user1.example.com
user2.example.com
and also have custom routes like user1.example.com/login
This works well so far, however when I add custom routes they do not work. I have searched and read a lot but seems there is something I am missing. Here is what I have so far:
//my routes in routes.ini
[development]
routes.login.type = "Zend_Controller_Router_Route"
routes.login.route = "/login"
routes.login.defaults.controller = "user"
routes.login.defaults.action = "login"
//This part in Bootstrap file
$this->bootstrap('frontController');
$router = $this->frontController->getRouter();
$routerConfig = new Zend_Config_Ini(
APPLICATION_PATH . '/configs/routes.ini',
'production'
);
//I create a default route
$routeDefault = new Zend_Controller_Router_Route_Module(
array(),
$this->frontController->getDispatcher(),
$this->frontController->getRequest()
);
$router->addConfig($routerConfig, 'routes');
// hostname route
$hostnameRoute = new Zend_Controller_Router_Route_Hostname(
':username.mysite.com',
array(
'module' => 'default',
'controller' => 'index',
'action' => 'index',
)
);
//I add the default route.
$router->addRoute('default', $routeDefault);
//I chain the routes so that all routes have subdomain routing too
foreach ($router->getRoutes() as $key => $theroute) {
$router->addRoute($key, $hostnameRoute->chain($theroute));
}
When I go to a custom route like http://user1.example.com/login I get the error: 'Invalid controller specified (login)' which means my custom route is not being recognized. I am also not sure if the way I am adding the default route is correct and necessary. If I remove that code then it doesn't work. So my problem really is that I would like my hostname matching, custom routes and default routes to all work. If you can spot where I'm going wrong please help, I have read previous related posts all over on routes, chaining, default routes etc (including this very related one: How do I write Routing Chains for a Subdomain in Zend Framework in a routing INI file?) but haven't found the solution so far.
You should be able to setup your routing using a custom param in the route:
routes.testdynamicsubdomain.type = "Zend_Controller_Router_Route_Hostname"
routes.testdynamicsubdomain.route = ":subdomain.domain.dev"
routes.testdynamicsubdomain.defaults.module = public
routes.testdynamicsubdomain.defaults.controller = index
routes.testdynamicsubdomain.defaults.action = index
If your apache/hostfile etc are configured correctly going to test.domain.dev should load the index action in your indexController where you could get the :subdomain param:
echo $this->getRequest()->getParam('subdomain');
Also, as you discovered, the order of the routes is very important. See also Zend Router precedence for more info about this.

How to route multi subdomain with zend router hostname

I need to create routing in Zend to simply copy the current live site url structure which is sadly inconsistent
What i want to do is to route subdomain as follow:
www.site.com -> static router
a.site.com & b.site.com -> category controller
c.site.com & d.site.com -> location controller
the rest sub domain -> user controller
could anyone guide me how to solve this, thanks.
UPDATE:
First thanks Fge, vote your answer, it works but i need some more advice:
Since i have many subdomains for each rules is there a better way than add the rules in looping
foreach($subdomains as $a){
$tr = new Zend_Controller_Router_Route_Hostname(
"$a.site.com",
array(
'module' => 'mod',
'controller' => 'ctrl',
'param_1' => $a
));
$router->addRoute($a,$tr);
}
How to combine it with other routing type to parse the parameters (chained?), something like http://a.site.com/:b/:c, i want t parse it to param_1 (a), param_2 (b), param_2 (c)
Note: Reverse Matching
Routes are
matched in reverse order so make sure
your most generic routes are defined
first.
(Zend_Controller_Router)
Thus you have to define the route for all other subdomains first, then the specific ones:
$user = new Zend_Controller_Router_Route_Hostname(
':subdomain.site.com',
array(
'controller' => 'user'
)
);
$location1 = new Zend_Controller_Router_Route_Hostname(
'c.site.com',
array(
'controller' => 'location'
)
);
$location1 = new Zend_Controller_Router_Route_Hostname(
'd.site.com',
array(
'controller' => 'location'
)
);
// other definitions with known subdomain
$router->addRoute($user); // most general one added first
$router->addRoute($location1);
$router->addRoute($location2);
// add all other subdomains
Update for the updated question:
1) This really depends on how different the parameters are you want to route a subdomain to. In your example you routed them all to the same model and controller and added the actual subdomain as a parameter. This can be done easily with the user-route i posted above. There the subdomain is set as parameter subdomain ($request->getParam("subdomain")). If you want the subdomains to be the action of a known controller/model you could replace :subdomain with :action. But as soon as you have other controllers/models for each subdomain, I'm affraid you have to loop over them (or use a config file). For the example you provided in the question, the route simply could look like this:
$user = new Zend_Controller_Router_Route_Hostname(
':param1.site.com',
array(
'controller' => 'user'
)
);
// routes "subdomain".site.com to defaultModul/userController/indexAction with additional parameter param1 => subdomain.
As long as you don't have any schema in your subdomains it's very difficult to route them in a general way.
2) That's an example where router chains come into play. The outer route would be the hostname route which handles the subdomain and the inner route would handle the :a/:b part. This could look like this for example:
$user->chain(new Zend_Controller_Router_Route(':a/:b'));