简体   繁体   English

在zend框架的url中添加语言参数

[英]Add a language parameter in url in zend framework

I have a site in zend framework . 我在zend framework中有一个站点。 Now I am making site in multiple language. 现在,我正在用多种语言制作网站。 For it I need to modify the url. 为此,我需要修改URL。

For example if sitename is www.example.com then i want to make it like 例如,如果站点名称是www.example.com,那么我想使其像

www.example.com/ch 
www.example.com/fr

There can be some work around it that you can ask me to create a folder name ch and put a copy of code inside it. 可能有一些解决方法,您可以要求我创建一个文件夹名称ch并将代码副本放入其中。 But for it I have to manage multiple folder when updating files on server. 但是为此,我必须在更新服务器上的文件时管理多个文件夹。

What is the best or correct way to do it ? 最好或正确的方法是什么?

My routs code is 我的溃败代码是

public function _initRouter() {
        $frontController = Zend_Controller_Front::getInstance();
        $router = $frontController->getRouter();
        $routes = array(
            'page' => new Zend_Controller_Router_Route('page/:slug', array('controller' => 'staticpage', 'action' => 'page', 'slug' => ''))
        );


        $router->addRoutes($routes);

    }

Thanks 谢谢

You have to add the language as parameter in your route(s). 您必须在路线中添加语言作为参数。 Here is an example: http://devzone.zend.com/1765/chaining-language-with-default-route/ 这是一个示例: http : //devzone.zend.com/1765/chaining-language-with-default-route/

You need a function to get a user choice of a language and a default language used if a user just starts with example.com. 如果用户只是从example.com开始,则需要一个函数来让用户选择一种语言和一种默认语言。

You may want to get the current browser and Language Header from the users HTTP request. 您可能希望从用户的HTTP请求中获取当前的浏览器和语言标题。

Take a look at Zend_Locale and Zend_Translate. 看一下Zend_Locale和Zend_Translate。

You can use something like $locale = new Zend_Locale('browser'); 您可以使用$ locale = new Zend_Locale('browser');之类的东西。 to detect the users browser language. 检测用户的浏览器语言。

Then look if Zend_Translate or your translation engine has the language available and set it to a cookie or session to store the date. 然后查看Zend_Translate或您的翻译引擎是否有可用的语言,并将其设置为cookie或会话以存储日期。

If the user then navigate to some language change site like example.com/?language=en you may want to set the locale based on the user choice and recheck if available in your translations. 如果用户随后导航到某些语言更改站点,例如example.com/?language=zh-CN,则您可能希望根据用户的选择来设置语言环境,然后重新检查翻译中是否可用。

If not, get back to original default language and present an error page or something like that. 如果不是,请返回原始默认语言并显示错误页面或类似内容。

If you want to get your Zend_Router urls to be language dependent, which might be a bad choice because of copy paste, backlinks or forum posts of your links, you need to add something before each route. 如果您想让Zend_Router网址依赖于语言,由于复制粘贴,反向链接或链接的论坛帖子,这可能是一个糟糕的选择,则需要在每条路由之前添加一些内容。

In my Applications i use something like the following in my main bootstrap.php file. 在我的应用程序中,我在主bootstrap.php文件中使用类似以下内容的东西。 I've cut some parts of to keep it simple. 为了简化起见,我删减了部分内容。

protected function _initTranslate() {
    $session = new Zend_Session_Namespace("globals");
    // Get current registry
    $registry = Zend_Registry::getInstance();
    /**
     * Set application wide source string language
     * i.e. $this->translate('Hallo ich bin ein deutscher String!');
     */
    if(!$session->current_language) {
        try {
            $locale = new Zend_Locale('browser'); //detect browser language
        }
        catch (Zend_Locale_Exception $e) {
            //FIXME: get from db or application.ini
            $locale = new Zend_Locale('en_GB');  //use the default language
        }
    }
    else {
        $locale = new Zend_Locale($session->current_language);
    }

    $translate = new Zend_Translate(
        array(
            'adapter' => 'array',
            'content' => realpath(APPLICATION_PATH . '/../data/i18n/'),
            'locale'  => $locale,
            'scan'    => Zend_Translate::LOCALE_DIRECTORY,
            'reload'  => false,
            'disableNotices' => true, //dont get exception if language is not available
            'logUntranslated' => false //log untranslated values
        )
    );

    if(!$translate->isAvailable($locale->getLanguage())) {
        $locale = new Zend_Locale('en_GB');  //default
    }

    $translate->setLocale($locale);

    $session->current_language = $locale->getLanguage();

    //Set validation messages
    Zend_Validate_Abstract::setDefaultTranslator($translate);
    //Max lenght of Zend_Form Error Messages (truncated with ... ending)
    Zend_Validate::setMessageLength(100);
    //Zend_Form Validation messages get translated into the user language
    Zend_Form::setDefaultTranslator($translate);

    /**
     * Both of these registry keys are magical and makes do automagical things.
     */
    $registry->set('Zend_Locale', $locale);
    $registry->set('Zend_Translate', $translate);

    return $translate;
}

This is for the default translation setup of each visitor. 这是每个访客的默认翻译设置。

To set a user language depending on some HTTP parameters, I decided to create a Plugin, which will run on each request, see if the global language parameter is set (key=_language) and try setting the new language. 为了根据某些HTTP参数设置用户语言,我决定创建一个插件,该插件将在每个请求上运行,查看是否设置了全局语言参数(key = _language),然后尝试设置新语言。

I then redirect the user to the new route, depending on his choice. 然后,根据用户的选择,将用户重定向到新路由。

So, if the user click on the link for english language (example.com/de/test/123?_language=en) he will get redirected to example.com/en/test/123. 因此,如果用户单击英语链接(example.com/de/test/123?_language=zh-CN),他将被重定向到example.com/en/test/123。

class Application_Plugin_Translate extends Core_Controller_Plugin_Abstract {

    public function preDispatch(Zend_Controller_Request_Abstract $request) {
        $frontController = Zend_Controller_Front::getInstance();

        // Get the registry object (global vars)
        $registry = Zend_Registry::getInstance();

        // Get our translate object from registry (set in bootstrap)
        $translate = $registry->get('Zend_Translate');
        // Get our locale object from registry (set in bootstrap)
        $locale = $registry->get('Zend_Locale');

        // Create Session block and save the current_language
        $session = new Zend_Session_Namespace('globals');

        //get the current language param from request object ($_REQUEST)
        $language = $request->getParam('_language',$session->current_language);
        // see if a language file is available for translate (scan auto)
        if($translate->isAvailable($language)) {
            //update global locale
            $locale = $registry->get('Zend_Locale');
            $locale->setLocale($language);
            $registry->set('Zend_Locale', $locale);

            //update global translate
            $translate = $registry->get('Zend_Translate');
            $translate->setLocale($locale);
            $registry->set('Zend_Translate', $translate);

            //language changed
            if($language!=$session->current_language) {
                //update session
                $session->current_language = $language;

                $redirector = new Zend_Controller_Action_Helper_Redirector;
                $redirector->gotoRouteAndExit(array());
            }
        }
        else {
            $request->setParam('_language', '');
            unset($session->current_language);

            $redirector = new Zend_Controller_Action_Helper_Redirector;
            $redirector->gotoRouteAndExit(array());
        }
    }
}

And finally, to prepare your router with the new language routes, you need to setup a base language route and chain your other language depending routes. 最后,要为路由器准备新的语言路由,您需要设置基本语言路由并根据其他路由链接其他语言。

public function _initRouter() {
    $frontController = Zend_Controller_Front::getInstance();
    $router = $frontController->getRouter();

    $languageRoute = new Zend_Controller_Router_Route(
        ':language',
        array(
            'language' => "de"
        ),
        array('language' => '[a-z]{2}')
    );

    $defaultRoute = new Zend_Controller_Router_Route(
        ':@controller/:@action/*',
        array(
            'module' => 'default',
            'controller' => 'index',
            'action' => 'index'
        )
    );
    $router->addRoute(
        'default',
        $defaultRoute
    );

    $languageDefaultRoute = $languageRoute->chain($defaultRoute);

    $router->addRoute(
        'language',
        $languageDefaultRoute
    );
}

Good luck with your project, hope it will help you and others! 祝您项目顺利,希望它对您和其他人有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM