cuongnd88/jutility

Laravel 日本工具

1.4 2021-07-05 07:40 UTC

This package is auto-updated.

Last update: 2024-09-05 16:17:02 UTC


README

本软件包提供了一种方便的方式获取日本工具,如日本邮政编码、日本本地化、CSV

安装

1-使用Composer安装cuongnd88/jutility

$ composer require cuongnd88/jutility

2-您可以通过将其复制到本地配置目录来修改配置

php artisan vendor:publish --provider="Cuongnd88\Jutility\JutilityServiceProvider"

您可以通过添加--tag选项来选择工具

php artisan vendor:publish --provider="Cuongnd88\Jutility\JutilityServiceProvider" --tag=public

这里有3个选项

--tag=public是将JP postal工具通过javascript发布。

--tag=config是将JP postal工具通过php/laravel发布。

--tag=lang是将日本本地化工具发布。

示例用法

通过Javascript使用JP postal工具

使用JP postal工具,您可以通过邮政编码获取日本邮政数据。您只需要实现如下

resources/views/user/jpostal.blade.php

. . . .

    <div class="form-group row">
        <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('Post code') }}</label>

        <div class="col-md-6">
            <input id="zip" type="text" class="form-control" name="email" value="" onkeyup="JPostal.capture('#zip', ['#info'])">
        </div>
    </div>

    <div class="form-group row">
        <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Info') }}</label>

        <div class="col-md-6">
            <input id="info" type="text" class="form-control" name="info">
        </div>
    </div>

. . . .
<script type="text/javascript" src="{{ asset('js/jpostal/jpostal.js') }}"></script>
<script type="text/javascript">
    JPostal.init();
</script>

JPostal.capture(zip, response):

zip:是一个字符串值,您可以为标识邮政编码的id或class赋值。例如:.zip#zip

response是获取数据(都道府县、市、区域和街道)的数组或函数。如果数组只有一个项目,它将以逗号分隔返回数据。数组有4个元素,因此它返回对应于都道府县、市、区域和街道的分离数据。如果响应是函数,它将回调。

MEMO您可以为zip和response参数使用id和class标志。您可以输入两种邮政编码格式(NNN-NNNN或NNNNNN)。

	<div class="col-md-6">
	    <input id="zip" type="text" class="form-control" name="email" value="" onkeyup="JPostal.capture('#zip', ['.prefecture', '.city', '.area', '.street'])">
	</div>
<script type="text/javascript">
    JPostal.init();

    $( "#zip" ).keyup(function() {
        JPostal.capture('#zip', function(data){
            console.log(data);
        });
    });
</script>

JPostal提供函数来选择与都道府县对应的市

JPostal.innerPrefecturesHtml(callback) .

JPostal.nnerCityHtmlByPref(prefTag, callback) .

. . . .
    <div class="form-group row">
        <label class="col-md-4 col-form-label text-md-right">{{ __('Prefecture') }}</label>

        <div class="col-md-6">
            <select class="form-control selectPrefecture" id="selectPrefecture">
            </select>
        </div>
    </div>

    <div class="form-group row">
        <label class="col-md-4 col-form-label text-md-right">{{ __('City') }}</label>

        <div class="col-md-6">
            <select class="form-control selectCity" id="selectCity">
            </select>
        </div>
    </div>
. . . .

<script type="text/javascript" src="{{ asset('js/jpostal/jpostal.js') }}"></script>
<script type="text/javascript">
    JPostal.init();

    JPostal.innerPrefecturesHtml(function(prefectures){
        let selectTag = '<option value="">Prefecture</option>';
        for (const [key, value] of Object.entries(prefectures)) {
            selectTag += `<option value="${key}">${value}</option>`;
        }
        $('#selectPrefecture').append(selectTag);
    });

    $("#selectPrefecture").change(function(){
        JPostal.innerCityHtmlByPref('#selectPrefecture', function(cities){
            let selectTag = '<option value="">City</option>';
            for (const item in cities) {
                const {id, name} = cities[item];
                selectTag += `<option value="${id}">${name}</option>`;
            }
            $('#selectCity').append(selectTag);
        });
    });
</script>

通过PHP/Laravel使用JP postal工具

有多个函数可以帮助您获取日本邮政编码

jpostal_pref($code = null):通过代码获取日本都道府县。

dump(jpostal_pref(47));

jpostal_pref_city($prefCode, $city = null):通过都道府县代码获取日本市。

dump(jpostal_pref_city(47));
dump(jpostal_pref_city(1, '01101));

jpostal_code($code):通过代码获取日本邮政数据。

    dump(jpostal_code('1200000'));
    dump(jpostal_code('120-0000'));

jlang($key):使用存储在resources/lang/{$currentLocale}/目录中的JSON文件作为键的翻译字符串。

    dump(jlang('Add Team Member'));

日本本地化工具

cuongnd88/jutility软件包提供了一种方便的方式来检索日语文本。默认语言存储在config/app.php配置文件中。您可以根据应用程序的需求修改此值。

. . . .
    'locale' => 'ja',
. . . .

语言字符串存储在resources/lang目录内的文件中。

/resources
    /lang
        /en
            messages.php
        /ja
            messages.php

CSV

CSV实用工具支持读取、验证和获取CSV文件。您必须在config/csv.php中设置验证器。请参阅默认设置。

return [
    /*
    |--------------------------------------------------------------------------
    | UTF-8 Bom
    |--------------------------------------------------------------------------
    |
    | The UTF-8 BOM is a sequence of bytes at the start of a text stream (0xEF, 0xBB, 0xBF)
    | that allows the reader to more reliably guess a file as being encoded in UTF-8.
    | Suitable for exporting Japanese data
    |
    */
    'utf-8-bom' => false,

    /*
    |--------------------------------------------------------------------------
    | Validator Support
    |--------------------------------------------------------------------------
    |
    | This is a sample defines how to validate CSV data:
    | - `user.header` is to identify the format of CSV file, that compare the standard header to the CSV header.
    | The "Invalid Header" message of Exception is threw if there is an error
    |
    | - `user.validator` is based on Laravel Validator. If you have multiple user tables or models you may configure multiple
    |       + `user.validator.rules`: set the Laravel validation rules
    |       + `user.validator.messages`: customize the Laravel default error messages
    |       + `user.validator.attributes`: customize the validation attributes
    */
    'user' => [
        'header' => [
            'fname' => 'First Name',
            'lname' => 'Last Name',
            'email' => 'Email',
        ],
        'validator' => [
            'rules' => [
                'fname' => 'required',
                'lname' => 'required',
                'email' => 'required|email',
            ],
            'messages' => [],
            'attributes' => [],
        ],
    ],
];

CSV是一个门面,它提供了从容器中访问对象的方法。您只需要在文件顶部导入CSV门面。

. . . .
use Cuongnd88\Jutility\Facades\CSV;

class UserController extends Controller
{
    . . . .
    public function postCSV(Request $request)
    {
        $csv = CSV::read(
                    $request->csv,
                    config('csv.user.header'),
                    config('csv.user.validator')
                )->filter();
        dump($csv);
    }
}
. . . .

read($file, array $standardHeader = [], $validatorConfig = null):读取CSV文件,返回CSV对象。

filter():过滤CSV数据,返回一个数组['validated' => [...], 'error' => [...]]

get():获取CSV数据(包括验证和错误数据),除了CSV标题行,返回一个数组。

validatorErrors():获取验证错误,返回一个数组。

    public function postCSV(Request $request)
    {
        $csv = CSV::read(
                    $request->csv,
                    config('csv.user.header'),
                    config('csv.user.validator')
                );
        $data = $csv->get();
        dump($data);
        $errorList = $csv->validatorErrors();
        dump($errorList);
    }

MEMO:CSV返回一个数组数据(或错误列表),索引数组是CSV文件的行号。

save(string $fileName, array $data, $header = null): 将数据导出到CSV文件。

    public function downloadCSV()
    {
        $data = User::all()->toArray();
        $header = ['ID','Fullname','Email','Mobile number', 'Email verified data time', 'Created date time', 'Updated date time'];
        CSV::save('user-data', $data, $header);
    }

示例

以下是示例源代码。

JPostal工具

CSV工具