在ap框架中使用composer

1.以使用 "illuminate/validation": "5.5.x-dev"为例

composer require "illuminate/validation": "5.5.x-dev"

会在当前目录下生成vendor目录:
重点是autoload.php

在bootstrap.php 中添加:
/**
* @param Dispatcher $dispatcher
*
*/
function _initComposerAutoload(Ap_Dispatcher $dispatcher)
{
$autoload = APP_PATH . '/xuperedge/vendor/autoload.php';//xuperedge 为项目目录 ps 没有找到一个可以指向这个目录的全局变量,因为bootstrap.php是在项目之外的
if (file_exists($autoload)) {
Ap_Loader::import($autoload);
}
}

2.创建验证类文件
use \Illuminate\Validation\Factory as validation;

class Xuperedge_Validator extends validation
{

/***
* 创建实例
*
* @return \Illuminate\Validation\Factory
*/
public static function getInstance()
{
static $validator = null;
if ($validator === null) {
$test_translation_path = __DIR__ . '/lang';
$test_translation_locale = 'en';
$translation_file_loader = new \Illuminate\Translation\FileLoader(new \Illuminate\Filesystem\Filesystem, $test_translation_path);
$translator = new \Illuminate\Translation\Translator($translation_file_loader, $test_translation_locale);
$validator = new \Illuminate\Validation\Factory($translator);
}
return $validator;
}

/**
* @param array $rules 验证规则
* @param array $data 验证数据
* @return bool
*/
    public static function validators($arrInput, $rules, $message)
    {
    $errorMessage = self::getInstance()->make($arrInput, $rules, $message)->getMessageBag();
    $errorMessage = json_decode(json_encode($errorMessage),true);
    if (!empty($errorMessage)) {
     foreach ($errorMessage as $name => $message){
   $msg = $name.$message[0];
   }
  throw new Exception($msg, 1);
  }
}

}

3.使用Xuperedge_Validator验证提交的数据
/**
*
* @param input
* @return result
*
**/
public function execute()
{
header("Content-type: application/json");
try {
$arrRequest = Saf_SmartMain::getCgi();
$arrInput = $arrRequest['get'];
//验证规则
$rules = [
'name' => 'required|string|min:2|max:5',
];

$message = [
'name.required' => '名字必填',
'name.string' => '类型错误必填',
'name.min' => '长度错误',
];
Xuperedge_Validator::validators($arrInput, $rules, $message);
$data = [];//请求都数据
echo json_encode(
array(
'status' => 0,
'message' => 'success',
'data' => $data,
)
);
} catch (\Exception $e) {
echo json_encode(
array(
'status' => $e->getCode(),
'message' => $e->getMessage(),
)
);
}
}
 



posted @ 2019-05-24 16:08  花泪哲  阅读(692)  评论(0)    收藏  举报