正确使用 zend 框架中的语言

发布于 2024-11-14 21:50:28 字数 2680 浏览 0 评论 0原文

我有一个带有两个模块(管理和公共)的 Zend 应用程序,对于公共,我有以下插件来解析我的友好 URL:

class Custom_Controller_Plugin_Initializer extends Zend_Controller_Plugin_Abstract {

    protected $_front;
    protected $_request;

    public function __construct() {
        $this->_front = Zend_Controller_Front::getInstance();
        $this->_request = $this->_front->getRequest();        
    }

    public function preDispatch(Zend_Controller_Request_Abstract $request) {
    //checking if the url ends with "/"      
        $requestUri = $this->_request->getRequestUri();
        $path = parse_url($requestUri, PHP_URL_PATH);
        $query = parse_url($requestUri, PHP_URL_QUERY);
        if (substr($path, -1) != '/') {
            header('location: ' . $path . (isset($query) ? '/?' . $query : '/'));
            die();
        }
// exploding the uri to get the parts.        
        $uri = explode('/', substr($path, strlen(Zend_Controller_Front::getInstance()->getBaseUrl()) + 1));


        $modelLanguage = new Model_Db_Language();
    //checking if the first part is of 2 characters and if it's a registered language
        if ($modelLanguage->checkLanguage($uri[0])) {            
            $language = $uri[0];
            unset($uri[0]); //deleting the language from the uri.
            $uri = array_values($uri);
        } else {
            $language = $modelLanguage->autoLanguage();
            if (!$uri[0] == '' && (strlen($uri[0]) == 2)) {
                $uri[0] = $language;
                header('location: ' . Zend_Controller_Front::getInstance()->getBaseUrl() . '/' . implode($uri) . (isset($query) ? '/?' . $query : '/'));
                die();
            }
        }

//remember that the language was deleted from the uri
        $this->_request->setParam('requestUri', implode('/', $uri));

        switch ($uri[0]) {
            case 'search':
                unset($uri[0]);
                $this->_request->setParam('s', urldecode($uri[2]));
                $this->_request->setModuleName('public');
                $this->_request->setControllerName('content');
                $this->_request->setActionName('search');
                $this->_request->setParam('template', 'search');
                break;
        }
        $this->_initTranslation($language);
            $this->_initInterface();
}}

如果我想使用像 domain.com/en/about-us 这样的结构,它非常有用/mission/ 因为我可以解析 url 并获取第一个参数“en”,然后找到与“about-us/mission”关联的页面,但是如果我想使用怎么办domain.com/en/user/profile/id/1/,Zend 将“en”设置为控制器,将“user”设置为操作。如何正确设置 url 中的语言?

I have an Zend application with two modules (admin and public) and for public I have the following plugin to parse my friendly-url:

class Custom_Controller_Plugin_Initializer extends Zend_Controller_Plugin_Abstract {

    protected $_front;
    protected $_request;

    public function __construct() {
        $this->_front = Zend_Controller_Front::getInstance();
        $this->_request = $this->_front->getRequest();        
    }

    public function preDispatch(Zend_Controller_Request_Abstract $request) {
    //checking if the url ends with "/"      
        $requestUri = $this->_request->getRequestUri();
        $path = parse_url($requestUri, PHP_URL_PATH);
        $query = parse_url($requestUri, PHP_URL_QUERY);
        if (substr($path, -1) != '/') {
            header('location: ' . $path . (isset($query) ? '/?' . $query : '/'));
            die();
        }
// exploding the uri to get the parts.        
        $uri = explode('/', substr($path, strlen(Zend_Controller_Front::getInstance()->getBaseUrl()) + 1));


        $modelLanguage = new Model_Db_Language();
    //checking if the first part is of 2 characters and if it's a registered language
        if ($modelLanguage->checkLanguage($uri[0])) {            
            $language = $uri[0];
            unset($uri[0]); //deleting the language from the uri.
            $uri = array_values($uri);
        } else {
            $language = $modelLanguage->autoLanguage();
            if (!$uri[0] == '' && (strlen($uri[0]) == 2)) {
                $uri[0] = $language;
                header('location: ' . Zend_Controller_Front::getInstance()->getBaseUrl() . '/' . implode($uri) . (isset($query) ? '/?' . $query : '/'));
                die();
            }
        }

//remember that the language was deleted from the uri
        $this->_request->setParam('requestUri', implode('/', $uri));

        switch ($uri[0]) {
            case 'search':
                unset($uri[0]);
                $this->_request->setParam('s', urldecode($uri[2]));
                $this->_request->setModuleName('public');
                $this->_request->setControllerName('content');
                $this->_request->setActionName('search');
                $this->_request->setParam('template', 'search');
                break;
        }
        $this->_initTranslation($language);
            $this->_initInterface();
}}

It is very usefull if I wanna use structure like domain.com/en/about-us/mision/ because I can parse the url and get the first param "en" and after that find the page associated to "about-us/mission" but what about if I wanna use domain.com/en/user/profile/id/1/, Zend set "en" as controller and "user" as action. How can I set the language in the url and properly?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏至、离别 2024-11-21 21:50:28

这是一个常见问题,所以让我概括和形式化一点。

假设您希望 Web 应用支持多种语言,并且有以下路由要求:

http://domain.com/language-code/controller-name/action-name

换句话说,您希望使用“语言代码”作为语言环境,并将前面的内容与默认的 Zend 模块路由结合起来。

假设您还想使用 Zend_Translate 根据语言环境提供翻译内容。

这是我使用的一些代码,经常“导出”到具有类似要求的项目中,我愿意进一步讨论。

相关配置项:

resources.frontController.plugins.Language = Plugin_Language
resources.frontController.actionHelperPaths.Controller_Helper = APPLICATION_PATH "/controllers/helpers"


; Locale

resources.locale.default = "en_US"
resources.locale.force = false

; Translate

resources.translate.adapter = "Csv"
resources.translate.data = APPLICATION_PATH "/languages"

resources.translate.locale = "auto"
resources.translate.disableNotices = true
resources.translate.scan = directory



; Routes

resources.router.routes.module.type = Zend_Controller_Router_Route_Module
resources.router.routes.module.abstract = On    

resources.router.routes.language.type = Zend_Controller_Router_Route
resources.router.routes.language.route = ":language"
resources.router.routes.language.reqs.language = "^[a-z]{2}$"
resources.router.routes.language.defaults.language = "en"

resources.router.routes.default.type = Zend_Controller_Router_Route_Chain
resources.router.routes.default.chain = "language,module"


; View

resources.view.helperPath.View_Helper = APPLICATION_PATH "/views/helpers"

这里注册的插件语言:

class Plugin_Language extends Zend_Controller_Plugin_Abstract {

    public function routeStartup(Zend_Controller_Request_Abstract $request){

        if (substr($request->getRequestUri(), 0, -1) == $request->getBaseUrl()){

            /* Access to the Base Url (no language information) */

            /* Get current locale language (autodetected) */
            $language = Zend_Registry::get("Zend_Locale")->getLanguage();


            /* If requested language isn't available set to the default one */
            if (!Zend_Registry::get('Zend_Translate')->isAvailable($language)){

                Zend_Registry::set(
                    "Zend_Locale", 
                    new Zend_Locale("default")
                );

                $language = Zend_Registry::get("Zend_Locale")->getLanguage();

                Zend_Registry::get("Zend_Translate")->setLocale(
                    Zend_Registry::get('Zend_Locale')
                );
            }


            /* Modifiy Request Uri with Language info from current Locale */
            $request->setRequestUri($request->getRequestUri().$language."/");
            $request->setParam("language", $language);

        }
    }


    public function routeShutdown(Zend_Controller_Request_Abstract $request){

        /* Get language from request param */
        $language = $request->getParam("language");

        /* If requested language isn't available set to the default one */
        if (!Zend_Registry::get('Zend_Translate')->isAvailable($language))
            throw new Zend_Controller_Router_Exception('Translation language is not available', 404);

        /* Set the locale */ 

        Zend_Registry::set(
                "Zend_Locale",
                new Zend_Locale($language)
        );

        /* Set the traslator */ 

        Zend_Registry::get("Zend_Translate")->setLocale(
                Zend_Registry::get("Zend_Locale")
        );


    }

}

操作助手:

class Controller_Helper_Language extends Zend_Controller_Action_Helper_Abstract {

    /**
     * 
     * Get Current language
     * 
     * @return mixed string|null
     */
    public function getCurrent(){

        if (!Zend_Registry::isRegistered("Zend_Locale"))
            return null;

        return Zend_Registry::get("Zend_Locale")->getLanguage();

    }

    /** 
     * 
     * Get translator 
     * 
     * @return mixed Zend_Translate|null
     * 
     */
    public function getTranslator(){

        if (!Zend_Registry::isRegistered("Zend_Translate"))
            return null;

        return Zend_Registry::get("Zend_Translate");

    }

}

查看 url 助手(覆盖默认的)。您必须根据您正在使用的新路由相应地编写您的网址:

    class View_Helper_Url extends Zend_View_Helper_Url {

    protected function _getCurrentLanguage(){

        return Zend_Controller_Action_HelperBroker::getStaticHelper('Language')
            ->getCurrent();

    }

    public function Url($urlOptions = array(), $name = null, $reset = true, $encode = true){

        $urlOptions = array_merge(
            array(
                "language" => $this->_getCurrentLanguage()
            ),
            $urlOptions
        );

        return parent::url($urlOptions,$name,$reset,$encode);

    }

}

希望这会有所帮助。

This is a common problem so let me generalize and formalize a little bit.

Let's say you want your web app to support multiple languages and you have the following routing requirements:

http://domain.com/language-code/controller-name/action-name

In other words you want to use "language-code" as locale and combine the previous with the default Zend module routing.

Let's assume you also want to use Zend_Translate to provide translated content according to the locale.

Here is some code I use and often "export" into project with similar requirements, I'm open to discuss further.

Relevant config items:

resources.frontController.plugins.Language = Plugin_Language
resources.frontController.actionHelperPaths.Controller_Helper = APPLICATION_PATH "/controllers/helpers"


; Locale

resources.locale.default = "en_US"
resources.locale.force = false

; Translate

resources.translate.adapter = "Csv"
resources.translate.data = APPLICATION_PATH "/languages"

resources.translate.locale = "auto"
resources.translate.disableNotices = true
resources.translate.scan = directory



; Routes

resources.router.routes.module.type = Zend_Controller_Router_Route_Module
resources.router.routes.module.abstract = On    

resources.router.routes.language.type = Zend_Controller_Router_Route
resources.router.routes.language.route = ":language"
resources.router.routes.language.reqs.language = "^[a-z]{2}$"
resources.router.routes.language.defaults.language = "en"

resources.router.routes.default.type = Zend_Controller_Router_Route_Chain
resources.router.routes.default.chain = "language,module"


; View

resources.view.helperPath.View_Helper = APPLICATION_PATH "/views/helpers"

Here the registered Plugin language:

class Plugin_Language extends Zend_Controller_Plugin_Abstract {

    public function routeStartup(Zend_Controller_Request_Abstract $request){

        if (substr($request->getRequestUri(), 0, -1) == $request->getBaseUrl()){

            /* Access to the Base Url (no language information) */

            /* Get current locale language (autodetected) */
            $language = Zend_Registry::get("Zend_Locale")->getLanguage();


            /* If requested language isn't available set to the default one */
            if (!Zend_Registry::get('Zend_Translate')->isAvailable($language)){

                Zend_Registry::set(
                    "Zend_Locale", 
                    new Zend_Locale("default")
                );

                $language = Zend_Registry::get("Zend_Locale")->getLanguage();

                Zend_Registry::get("Zend_Translate")->setLocale(
                    Zend_Registry::get('Zend_Locale')
                );
            }


            /* Modifiy Request Uri with Language info from current Locale */
            $request->setRequestUri($request->getRequestUri().$language."/");
            $request->setParam("language", $language);

        }
    }


    public function routeShutdown(Zend_Controller_Request_Abstract $request){

        /* Get language from request param */
        $language = $request->getParam("language");

        /* If requested language isn't available set to the default one */
        if (!Zend_Registry::get('Zend_Translate')->isAvailable($language))
            throw new Zend_Controller_Router_Exception('Translation language is not available', 404);

        /* Set the locale */ 

        Zend_Registry::set(
                "Zend_Locale",
                new Zend_Locale($language)
        );

        /* Set the traslator */ 

        Zend_Registry::get("Zend_Translate")->setLocale(
                Zend_Registry::get("Zend_Locale")
        );


    }

}

The action helper:

class Controller_Helper_Language extends Zend_Controller_Action_Helper_Abstract {

    /**
     * 
     * Get Current language
     * 
     * @return mixed string|null
     */
    public function getCurrent(){

        if (!Zend_Registry::isRegistered("Zend_Locale"))
            return null;

        return Zend_Registry::get("Zend_Locale")->getLanguage();

    }

    /** 
     * 
     * Get translator 
     * 
     * @return mixed Zend_Translate|null
     * 
     */
    public function getTranslator(){

        if (!Zend_Registry::isRegistered("Zend_Translate"))
            return null;

        return Zend_Registry::get("Zend_Translate");

    }

}

The view url helper (overriding default one). You have to write your urls accordingly with the new routing you are using:

    class View_Helper_Url extends Zend_View_Helper_Url {

    protected function _getCurrentLanguage(){

        return Zend_Controller_Action_HelperBroker::getStaticHelper('Language')
            ->getCurrent();

    }

    public function Url($urlOptions = array(), $name = null, $reset = true, $encode = true){

        $urlOptions = array_merge(
            array(
                "language" => $this->_getCurrentLanguage()
            ),
            $urlOptions
        );

        return parent::url($urlOptions,$name,$reset,$encode);

    }

}

Hope this help.

伊面 2024-11-21 21:50:28

我想说你应该使用自定义路由器。这就是路由器的用途——从 URI 确定参数。现在你就让路由器无缘无故地工作。因为你随后改变了它的工作结果。

编写自定义路由器并不那么困难,我建议您应该这样做。你可以在那里写一些类似的东西:

  1. explode by /
  2. is first part "en", "de" or "es", if so set lang = $arr[0]
  3. work as default Route for Zend_Router

并且你可以添加更多选项。此外,匹配可能会更快,因为您可以逻辑地构建 URI 分解。普通路由器是愚蠢的 - 它只是匹配 URI 来路由正则表达式,并在找到匹配时停止。

I'd say that you should use custom router. This is what router is for - determining parameters from URI. Now you just let the router do work for no reason. Because you then change the result of it's work.

Writing custom router is not that difficult and I would suggest you should do so. You can write there something like:

  1. explode by /
  2. is first part "en", "de" or "es", if so set lang = $arr[0]
  3. work as default route for Zend_Router

And you can add many more options. Also matching may be much faster because you can logically strucutre the URI decomposition. Normal router is dumb - it just matches URI to route regex and stops when match is found.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文