民间传说/eloquent-localizable

Laravel 4 和 5 的包,用于向 Eloquent 模型添加本地化功能

v0.2.2 2015-06-20 15:45 UTC

This package is auto-updated.

Last update: 2024-09-19 08:50:02 UTC


README

简单Laravel 4 和 5 包,用于向 Eloquent 模型添加本地化功能

安装

依赖

安装

1- 使用 Composer 安装包

$ composer require folklore/eloquent-localizable

使用方法

配置

此包使用一个特性(Trait)来向您的 Eloquent 模型添加本地化功能。基本上,它将为您的模型添加一个 locales 关联并提供一个简单的同步方法。

例如,如果您有一个 Page 模型,并且想要添加本地化的 titledescription。您首先将特性添加到您的 Page 类中。

use Folklore\EloquentLocalizable\LocalizableTrait;

class Page extends Eloquent {
    
    use LocalizableTrait;
    
}

默认情况下,特性将查找一个 [MODEL_NAME]Locale 模型。所以在这个例子中,它将查找一个 PageLocale。只需在您的 Page 模型旁边创建一个 PageLocale 类即可。

use Folklore\EloquentLocalizable\LocaleModel;

class PageLocale extends LocaleModel {
    
    protected $table = 'pages_locales';
    
}

您可以通过覆盖 getLocaleModelClass 方法来更改本地化模型类。

use Folklore\EloquentLocalizable\LocalizableTrait;

class Page extends Eloquent {
    
    use LocalizableTrait;
    
    protected function getLocaleModelClass()
    {
        return 'App\Models\CustomLocaleModel';
    }
    
}

您还需要为您本地化创建一个表。根据示例,我们将为 pages_locales 表创建一个迁移。

Schema::create('pages_locales', function(Blueprint $table)
{
	$table->increments('id');
	$table->integer('page_id')->unsigned();
	$table->string('locale',2);
	$table->string('title');
	$table->string('description');
	$table->timestamps();
	
	$table->index('page_id');
	$table->index('locale');
});

获取本地化

现在您可以在您的 Page 模型上使用本地化关系。

获取包含所有本地化的页面

$page = Page::with('locales')->first();

//Getting the title for a specific locale
echo $page->locales->fr->title;

//Looping through all locales
foreach($page->locales as $locale)
{
    echo $locale->locale.': '.$locale->title;
}

获取具有特定本地化的页面

$page = Page::withLocale('fr')->first();

//Getting a the title
echo $page->locale->fr->title;

如果您总是想要在获取页面时包含本地化。

use Folklore\EloquentLocalizable\LocalizableTrait;

class Page extends Eloquent {
    
    use LocalizableTrait;
    
    protected $with = ['locales'];
    
}

保存本地化

您可以使用 syncLocales 方法来保存您的本地化。

$locales = array(
    'en' => array(
        'title' => 'A page',
        'description' => 'This is the description of this page'
    ),
    'fr' => array(
        'title' => 'Une page',
        'description' => 'Ceci est la description de cette page'
    )
);

//or

$locales = array(
    array(
        'locale' => 'en',
        'title' => 'A page',
        'description' => 'This is the description of this page'
    ),
    array(
        'locale' => 'fr',
        'title' => 'Une page',
        'description' => 'Ceci est la description de cette page'
    )
);

$page = new Page();
$page->save(); //We need an id for this page, so we save before.

$page->syncLocales($locales);