Kohana 3.3.3 многоязычный сайт

0

Я новичок в Kohana, используя версию 3.3.3.1, я пытаюсь создать простой динамический сайт с содержимым/страницами, хранящимися в базе данных mySQL. Сайт должен иметь несколько языков. Я пробовал искать везде хорошее решение/модуль, но я не мог найти ничего, что работает с последней версией Kohana. Я пробовал также это: https://github.com/shockiii/kohana-multilang, но он не работает над последней коханой.

Я хочу поместить язык в URL как это (и, возможно, скрыть параметр для языка по умолчанию):

http://www.domain.com/topics/page-name-here.html   -- this would be default EN
http://www.domain.com/de/test/some-page-name-here.html
http://www.domain.com/fr/category/other-page-name-here.html

В моем bootstrap.php у меня есть следующий маршрут (перед добавлением логики языка):

Route::set('page', '(<category>)(/<pagename>.html)', array(
    'category' => '.*', 
    'pagename' => '.*'))
    ->defaults(array(
                'controller' => 'Page',
                'action' => 'index',
)); 

Я хочу, чтобы вся эта многоязычная логика была внутри модуля, если это было возможно. Но я читал о том, чтобы переопределить Request, URL, Route и другие классы, чтобы это сделать.

Как я могу это сделать? Что мне делать/менять и с чего начать?

Я знаю, что это более общий вопрос, но любая помощь или руководство очень ценятся.

Огромное спасибо!

Теги:
kohana-3.3

2 ответа

0
Лучший ответ

1) добавить <lang> в маршруты в bootstrap.php:

Route::set('default', '((<lang>)(/)(<controller>)(/<action>(/<id>)))', array('lang' => "({$langs_abr})",'id'=>'.+'))
    ->defaults(array(
        'lang'          => $default_lang,
        'controller'    => 'Welcome',
        'action'        => 'index',
    ));

- Определите $ default_lang как-то - я использую файл siteconfig.php, расположенный внутри application/config -see ниже.

2) Расширить/переопределить заводский метод в Контроллере запросов:

<?php defined('SYSPATH') or die('No direct script access.');

class Request extends Kohana_Request {
    /**
     * Main request singleton instance. If no URI is provided, the URI will
     * be automatically detected using PATH_INFO, REQUEST_URI, or PHP_SELF.
     *
     * @param   string   URI of the request
     * @return  Request
     */
    public static function factory( $uri = TRUE,$client_params = array(), $allow_external = TRUE, $injected_routes = array())
    {

        $instance = parent::factory($uri);

        $index_page     = Kohana::$index_file;
        $siteconfig     = Model_Siteconfig::load();
        $lang_uri_abbr  = $siteconfig['lang_uri_abbr'];
        $default_lang   = $siteconfig['language_abbr'];
        $lang_ignore    = $siteconfig['lang_ignore'];

        $ignore_urls    = $siteconfig['ignore_urls'];

        /* get the lang_abbr from uri segments */
        $segments = explode('/',$instance->detect_uri());

        $uri_detection  = array_intersect($segments, $ignore_urls);

        if(empty($uri_detection))
        {

            $lang_abbr = isset($segments[1]) ? $segments[1]:'';

            /* get current language */
            $cur_lang = $instance->param('lang',$default_lang);

            /* check for invalid abbreviation */
            if( ! isset($lang_uri_abbr[$lang_abbr]))
            {       
                /* check for abbreviation to be ignored */
                if ($cur_lang != $lang_ignore) {
                    /* check and set the default uri identifier */
                    $index_page .= empty($index_page) ? $default_lang : "/$default_lang";

                    /* redirect after inserting language id */
                    header('Location: '.URL::base().$index_page . $instance->detect_uri());
                    die();
                }
            }
        }

        return $instance;

    }
}

Я использую массив siteconfig с определениями языка:

array(
        'language_abbr'     => 'cs',
        'lang_uri_abbr'     => array("cs" => "česky", "en" => "english"),
        'lang_ignore'       => 'it', 
)

3) Расширить/переопределить метод "перенаправления" в классе контроллера для автоматического добавления языков:

<?php defined('SYSPATH') or die('No direct script access.');

class Controller extends Kohana_Controller {

    /**
     * Issues a HTTP redirect.
     *
     * Proxies to the [HTTP::redirect] method.
     *
     * @param  string  $uri   URI to redirect to
     * @param  int     $code  HTTP Status code to use for the redirect
     * @throws HTTP_Exception
     */
    public static function redirect($uri = '', $code = 302)
    {
        $lng = Request::current()->param('lang');
        return HTTP::redirect( (string) '/'.$lng.$uri, $code);
    }
}

Если вы будете использовать HTML-класс (например, для шаблонов), вы должны, вероятно, переопределить некоторые другие методы, такие как "якорь" для создания якорей с автоматическим добавлением языка:

<?php defined('SYSPATH') OR die('No direct script access.');

class HTML extends Kohana_HTML {

    /**
     * Create HTML link anchors. Note that the title is not escaped, to allow
     * HTML elements within links (images, etc).
     *
     *     echo HTML::anchor('/user/profile', 'My Profile');
     *
     * @param   string  $uri        URL or URI string
     * @param   string  $title      link text
     * @param   array   $attributes HTML anchor attributes
     * @param   mixed   $protocol   protocol to pass to URL::base()
     * @param   boolean $index      include the index page
     * @return  string
     * @uses    URL::base
     * @uses    URL::site
     * @uses    HTML::attributes
     */
    public static function anchor($uri, $title = NULL, array $attributes = NULL, $protocol = NULL, $index = FALSE)
    {

        //default language
        $lng = Request::current()->param('lang');

        if ($title === NULL)
        {
            // Use the URI as the title
            $title = $uri;
        }

        if ($uri === '')
        {
            // Only use the base URL
            $uri = URL::base($protocol, $index).$lng;
        }
        else
        {
            if (strpos($uri, '://') !== FALSE)
            {
                if (HTML::$windowed_urls === TRUE AND empty($attributes['target']))
                {
                    // Make the link open in a new window
                    $attributes['target'] = '_blank';
                }
            }
            elseif ($uri[0] !== '#')
            {
                // Make the URI absolute for non-id anchors
                $uri = URL::site($lng.$uri, $protocol, $index);
            }
        }

        // Add the sanitized link to the attributes
        $attributes['href'] = $uri;

        return '<a'.HTML::attributes($attributes).'>'.$title.'</a>';
    }

}
0

Я нашел отличный модуль, который работает с Kohana 3.3.3: https://github.com/creatoro/flexilang

Ещё вопросы

Сообщество Overcoder
Наверх
Меню