如何在Laravel之外使用illuminate組件詳解
當代框架基本都是有組件構(gòu)成,這使得框架變得更加靈活。The Laravel Components | github Laravel 中有不少優(yōu)質(zhì)組件,那如何在 Laravel 之外使用 illuminate 組件呢?
illuminate/validation
以 illuminate/validation 為例,validation 有豐富的數(shù)據(jù)驗證功能。
在項目的 composer.json 文件中添加:
...
"require": {
...
"illuminate/validation": "^5.8",
...
從 Laravel-Lang/lang 項目中復制需要的語言文件放到自己的項目中。
例如:在 Yii2 項目中,復制對應(yīng)語言文件到項目中的 assets/lang/zh-CN/validation.php。
創(chuàng)建 common/Validator.php:
namespace app\common;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Translation\FileLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Factory;
class Validator
{
private static $instance = null;
private function __construct()
{
}
public static function getInstance(): Factory
{
if (null === static::$instance) {
$translationPath = get_alias('@assets/lang');
$translationLocale = 'zh-CN';
$transFileLoader = new FileLoader(new Filesystem(), $translationPath);
$translator = new Translator($transFileLoader, $translationLocale);
static::$instance = new Factory($translator);
}
return static::$instance;
}
}
在全局函數(shù)文件添加:
// https://learnku.com/docs/laravel/5.8/validation/3899#manually-creating-validators
// $rules = [
// 'name' => 'required|string|min:2|max:5',
// 'code' => 'required|string|min:2|max:5',
// ];
function validator(array $data, array $rules, array $messages = [], array $customAttributes = [])
{
return \app\common\Validator::getInstance()->make($data, $rules, $messages, $customAttributes);
}
測試使用:
$rules = ['name' => 'required|numeric'];
$customAttributes = ['name' => 'My name'];
$messages = ['name.required' => 'A name is required',];
$validator = validator($data, $rules, $customAttributes, $messages);
if ($validator->fails()) {
$errors = $validator->errors()->all();
Response::error(Errors::ParamsInvalid, implode(',', $errors), $errors);
}
總結(jié)
到此這篇關(guān)于如何在Laravel之外使用illuminate組件的文章就介紹到這了,更多相關(guān)Laravel之外使用illuminate組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
php curl抓取網(wǎng)頁的介紹和推廣及使用CURL抓取淘寶頁面集成方法
抓取網(wǎng)頁內(nèi)容,分析網(wǎng)頁數(shù)據(jù)經(jīng)常使用php curl,簡潔易用,本篇文章通過代碼實例給大家講解 php curl抓取網(wǎng)頁的介紹和推廣及使用CURL抓取淘寶頁面集成方法,需要的朋友參考下2015-11-11
Laravel框架學習筆記(二)項目實戰(zhàn)之模型(Models)
上一篇已經(jīng)介紹開發(fā)環(huán)境的搭建,這篇將從項目實戰(zhàn)開發(fā),一步一步了解laravel框架。首先我們來了解下laravel框架的模型 (Models)2014-10-10
thinkphp隱藏index.php/home并允許訪問其他模塊的實現(xiàn)方法
這篇文章主要介紹了thinkphp隱藏index.php/home并允許訪問其他模塊的實現(xiàn)方法,想要達成的效果很簡單,我有兩個模塊,Home、Wechat。具體詳情請參考下本文。感興趣的朋友一起看看吧2016-10-10
php實現(xiàn)將數(shù)據(jù)做成json的格式給前端使用
今天小編就為大家分享一篇php實現(xiàn)將數(shù)據(jù)做成json的格式給前端使用方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
wordpress網(wǎng)站轉(zhuǎn)移到本地運行測試的方法
這篇文章主要為大家詳細介紹了wordpress網(wǎng)站轉(zhuǎn)移到本地運行測試的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03
PHP仿博客園 個人博客(1) 數(shù)據(jù)庫與界面設(shè)計
自學PHP大半年多了,斷斷續(xù)續(xù)地,但是最終還是堅定了我的想法,將PHP繼續(xù)下去,所以寫這個PHP的博客是為了找個穩(wěn)定的 PHP工作,不求工資多高,但求一收留之地2013-07-07

