Zend Framework: Zend_translate and routing related issue - zend-framework

I have implemented Zend_Navigation, Zend_Translate in my application.
The routing is setup in Bootstrap.php like below.
$fc = Zend_Controller_Front::getInstance();
$zl=new Zend_Locale();
Zend_Registry::set('Zend_Locale',$zl);
$lang=$zl->getLanguage().'_'.$zl->getRegion();
$router = $fc->getRouter();
$route = new Zend_Controller_Router_Route(':lang/:module/:controller/:action/*',
array(
'lang'=>$lang, 'module'=>'default', 'controller'=>'index', 'action'=>'index'
));
$router->addRoute('default', $route);
$fc->setRouter($router);
$fc->registerPlugin( new Plugin_LanguageSetup());
in LaunguageSetup Plugin i have defined the dispatchLoopStartup method to do the checking of the language param
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) {
$this->createLangUrl($request);
$this->_language = $request->getParam('lang');
if ((!isset($this->_language)) || !in_array($this->_language, $this->_languagesArray)) {
$this->_language = 'en_US';
$request->setParam('lang', 'en_US');
}
$file = APPLICATION_PATH.$this->_directory.$this->_language.'.csv';
$translate = new Zend_Translate('csv', $file, $this->_language);
Zend_Registry::set('Zend_Translate', $translate);
$zl = Zend_Registry::get('Zend_Locale');
$zl->setLocale($this->_language);
Zend_Registry::set('Zend_Locale', $zl);
// $fc = Zend_Controller_Front::getInstance();
// $router = $fc->getRouter();
// $route = new Zend_Controller_Router_Route(':lang/:module/:controller/:action/*', array(
// 'lang'=>$this->_language, 'module'=>'default', 'controller'=>'index', 'action'=>'index'
// ));
// $router->addRoute('default', $route);
// $fc->setRouter($router);
}
What happen is the language always have the default value, the 'lang' param never default lang value in route, even if i type it in the address bar manually i.e /en_US/module/controller/action/ It always get revert back to the default Zend_locale();
Only way i can fix it is to setup the route again in the plugin and inject a correct language value as default. Any Idea why?

try and do a var_dump of the 2 vars ( _language, _languagesArray ) before this line
if ((!isset($this->_language)) || !in_array($this->_language, $this->_languagesArray)) {
I suspect that there it should be the problem, because you put yor plugin on dispatchLoopStartup, and then the params might not be populated, i put my plugin on routeShutdown see my implementation of the languange plugin.

Sort of a partial solution.
in dispatchLoopStartup
add
$fc = Zend_Controller_Front::getInstance();
$router = $fc->getRouter();
$router->setGlobalParam('lang',$this->_language);
better than redefine and overwrite the route again and 'fake' the language param by changing the default 'lang' value.
it's just less than perfect. Zend_router suppose to pick up the 'lang' param and have them placed in Zend_navigation->menu();

Related

How to set router for earch module in zend framework

I have 1 zend (v1) application, and 2 module : default + admin
I want when call default module will be set router in configs/router/default.ini
and if in module admin do not any thing
I tried using plugin but it doesn't work
in my plugin
class Australian_Controller_Plugin_DefaultRouter extends Zend_Controller_Plugin_Abstract {
public function routeShutdown(Zend_Controller_Request_Abstract $request) {
$currModule = $request->getModuleName();
if ($currModule != 'default') {
return;
}
$fontController = Zend_Controller_Front::getInstance();
$router1 = new Zend_Controller_Router_Rewrite();
$fontController->getRouter()->removeDefaultRoutes();
$myRoutes = new Zend_Config_Ini(APPLICATION_PATH . '/configs/router/default.ini', 'production');
$router1->addConfig($myRoutes, 'routes');
$fontController->setRouter($router1);
}
}
and /default/Bootstrap.php
protected function _initRoutes() {
$fontController = Zend_Controller_Front::getInstance();
$fontController->registerPlugin(new Australian_Controller_Plugin_DefaultRouter());
}
thanks
Note that you are adding new router after Routing so Zend already decoded address using old routes. This way you can generate URLs using new routes, but they will not e recognized by Zend. You need to call $router->route($request); again to set module/controller/action using new set of routes.
Sadly this is not working when its called in routeShutdown and has to be added to preDispatch(). Sadly I'm quite new to Zend too and still not grasping why it is so.
Code i used:
$fontController = Zend_Controller_Front::getInstance();
$router = $fontController->getRouter();
$r = new Zend_Controller_Router_Route(
'/testnew',
array(
'module' => 'user',
'controller' => 'index',
'action' => 'myaccount',
));
$router->addRoute('testnew', $r);
$router->route($request);

Zend Framework Router Hostname and Multi-Language support

Last two days I was fighting with Zend Framework Router and still didn't find solution.
Existing project has 2 different modules which work with the same domain e.g. www.domain1.com:
default - Contains public information, can be accessed via www.domain1.com
admin - Administrator interface, can be accessed via www.domain1.com/admin
Project is multi-langual and to keep language code it is transmitted as first parameter of every URL, e.g. www.domain1.com/en/ www.domain1.com/en/admin
Part of code which takes care is next plugin:
class Foo_Plugin_Language extends Zend_Controller_Plugin_Abstract
{
const LANGUAGE_KEY = 'lang';
public function routeStartup(Zend_Controller_Request_Abstract $request)
{
$languagesRegexp = implode('|', array_map('preg_quote', $this->_bootstrap->getLanguages()));
$routeLang = new Zend_Controller_Router_Route(
':' . self::LANGUAGE_KEY,
array(self::LANGUAGE_KEY => $this->_bootstrap->getLanguage()->toString()),
array(self::LANGUAGE_KEY => $languagesRegexp)
);
$router = $this->getFrontController()->getRouter();
$router->addDefaultRoutes();
$chainSeparator = '/';
foreach ($router->getRoutes() as $name => $route) {
$chain = new Zend_Controller_Router_Route_Chain();
$chain
->chain($routeLang, $chainSeparator)
->chain($route, $chainSeparator);
$new_name = $this->_formatLanguageRoute($name);
$router->addRoute($new_name, $chain);
}
protected function _formatLanguageRoute($name)
{
$suffix = '_' . self::LANGUAGE_KEY;
if (substr($name, -strlen($suffix)) == $suffix) return $name;
return $name . '_' . self::LANGUAGE_KEY;
}
public function routeShutdown(Zend_Controller_Request_Abstract $request)
{
$lang = $request->getParam(self::LANGUAGE_KEY, null);
$this->_bootstrap->setLanguage($lang);
$actual_lang = $this->_bootstrap->getLanguage()->toString();
$router = $this->getFrontController()->getRouter();
$router->setGlobalParam(self::LANGUAGE_KEY, $lang);
// Do not redirect image resize requests OR get js, css files
if (preg_match('/.*\.(jpg|jpeg|gif|png|bmp|js|css)$/i', $request->getPathInfo())) {
return true;
}
// redirect to appropriate language
if ($lang != $actual_lang) {
$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$params = array(self::LANGUAGE_KEY => $actual_lang);
$route = $this->_formatLanguageRoute($router->getCurrentRouteName());
return $redirector->gotoRouteAndExit($params, $route, false);
}
}
}
One of the first question is what do you think about such way to provide multi-lang support. What I've noticed is that all this chains dramatically decrease operation speed of the server, response time from the server is about 4 seconds...
Main question is: Currently I have to implement such feature: I have domain www.domain2.com that should work just with single module e.g. "foobar"... and it should be available via second url... or, of course, it should work like www.domain1.com/en/foobar by default...
To provide this functionality in Bootstrap class I'be implemented such part of code
// Instantiate default module route
$routeDefault = new Zend_Controller_Router_Route_Module(
array(),
$front->getDispatcher(),
$front->getRequest()
);
$foobarHostname = new Zend_Controller_Router_Route_Hostname(
'www.domain2.com',
array(
'module' => 'foobar'
)
);
$router->addRoute("foobarHostname", $foobarHostname->chain($routeDefault));
And that is not working and as I've found routeDefault always rewrite found correct model name "foobar" with value "default"
Then I've implemented default router like this:
new Zend_Controller_Router_Route(
':controller/:action/*',
array(
'controller' => 'index',
'action' => 'index'
);
);
But that still didn't work, and started work without language only when I comment "routeStartup" method in Foo_Plugin_Language BUT I need language support, I've played a lot with all possible combinations of code and in the end made this to provide language support by default:
class Project_Controller_Router_Route extends Zend_Controller_Router_Route_Module
{
/**
* #param string $path
* #param bool $partial
* #return array
*/
public function match($path, $partial = false)
{
$result = array();
$languageRegexp = '%^\/([a-z]{2})(/.*)%i';
if (preg_match($languageRegexp, $path, $matches)) {
$result['lang'] = $matches[1];
$path = $matches[2];
}
$parentMatch = parent::match($path);
if (is_array($parentMatch)) {
$result = array_merge($result, $parentMatch);
}
return $result;
}
}
So language parameter was carefully extracted from path and regular processed left part as usual...
But when I did next code I was not able to get access to the foobar module via www.domain2.com url, because of module name in request was always "default"
$front = Zend_Controller_Front::getInstance();
/** #var Zend_Controller_Router_Rewrite $router */
$router = $front->getRouter();
$dispatcher = $front->getDispatcher();
$request = $front->getRequest();
$routerDefault = new Project_Controller_Router_Route(array(), $dispatcher, $request);
$router->removeDefaultRoutes();
$router->addRoute('default', $routerDefault);
$foobarHostname = new Zend_Controller_Router_Route_Hostname(
'www.domain2.com',
array(
'module' => 'foobar'
)
);
$router->addRoute("foobar", $foobarHostname->chain($routerDefault));
Instead of summary:
Problem is that I should implement feature that will provide access for the secondary domain to the specific module of ZendFramework, and I should save multi-language support. And I cannot find a way, how to manage all of this...
Secondary question is about performance of chain router, it makes site work very-very slow...
The way I have solved problem with multilanguage page is in this thread:
Working with multilanguage routers in Zend (last post).
Ofcourse my sollution need some caching to do, but I think it will solve your problem.
Cheers.

Force user to use language route

I am changing my application routes so that I can use subdirectories with gTLDs(example.com/de/) instead of URL params (example.com?loc=de). As It is in http://devzone.zend.com/1765/chaining-language-with-default-route/ , I used the following route configuration:
protected function _initRoutes() {
$locale = $this->getResource('locale');
// Create route with language id (lang)
$routeLang = new Zend_Controller_Router_Route(
':lang', array(
'lang' => $locale->getLanguage()
), array('lang' => '[a-z]{2}')
);
// Now get router from front controller
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
// Instantiate default module route
$routeDefault = new Zend_Controller_Router_Route_Module(
array(), $front->getDispatcher(), $front->getRequest()
);
// Chain it with language route
$routeLangDefault = $routeLang->chain($routeDefault);
// Add both language route chained with default route and
// plain language route
$router->addRoute('default', $routeLangDefault);
$router->addRoute('lang', $routeLang);
// Register plugin to handle language changes
$front->registerPlugin(new Sistema_Plugin_Language());
}
I am using baseUrl to whole website links.
However my old links(example.com/news/) returns an error saying "No route matched the request", How could I force the user or redirect the user to new URLs(example.com/en/news/)?

How to rename module admin in Zend Framework

I have a problem with URL rewrite in Zend Framework, I hope someone helps me solve that.
I need to rename module admin as admindev in URL apply for all controller and action.
Here my code write in Bootstrap.php:
public function _initModuleRoutes()
{
$this->bootstrap('FrontController');
$frontController = $this->getResource('FrontController');
$router = $frontController->getRouter();
$route = new Zend_Controller_Router_Route(
'admindev/:action/*',
array(
'module'=>'admin',
'controller'=>':controller',
'action'=>':action'
)
);
$router->addRoute('admin',$route);
return $router;
}
Thanks all,
You didn't specify the :controller parameter in the route.
Try it like that:
public function _initModuleRoutes()
{
$this->bootstrap('FrontController');
$frontController = $this->getResource('FrontController');
$router = $frontController->getRouter();
$route = new Zend_Controller_Router_Route(
'admindev/:controller/:action/*',
array(
'module'=>'admin',
'controller'=>':controller',
'action'=>':action'
)
);
$router->addRoute('admin',$route);
return $router;
}
Also you can achieve the same effect with application.ini configuration:
resources.router.routes.admindev.type = "Zend_Controller_Router_Route"
resources.router.routes.admindev.route = "/admindev/:controller/:action/*"
resources.router.routes.admindev.defaults.module = "admin"
Other application.ini tips and tricks here

Zend framework route

I have the following controllers in my modules..
UserController.php
AdminUserController.php
Now the route for admin controller goes to: module/admin-user/ (default behaviour)
How do I make a route so all admin- will be changed to:
/admin/module/user
You will have to write a custom route.
In code:
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$route = new Zend_Controller_Router_Route(
'admin/:module/user', array('controller' => 'admin-user'));
$router->addRoute('module-admin-router', $route);
In a .ini file (I like to keep mine separate from application.ini):
[routes]
routes.module-admin-router.type = "Zend_Controller_Router_Route"
routes.module-admin-router.route = "archive/:module/user"
routes.module-admin-router.defaults.controller = "admin-user"
Then you will have to bootstrap that application section to enable the routes;
protected function _initRoutes ()
{
// setup routes here.
$front = $this->getResource('frontcontroller');
$router = $front->getRouter();
$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/routes.ini', 'routes');
$router->addConfig($config->routes);
}
This route will match any admin/module/user request and send it to the AdminUserController within the matching module.
Something like that should work. Now if things get really complicated, you'll probably need to dig into the regex router - but this is as simple as I can think of it needing to be.