PHP中对进行链式验证(常见于登录的验证)
下面以表单提交进行演示
创建验证的抽象类`FormValidate
<?php
/**
* Created by PhpStorm.
* User: iamcyan
* Date: 2017/6/30
* Time: 13:19
*/
namespace App\Services\Validate;
use Illuminate\Http\Request;
/**
* Class TestValidtate
* @package App\Services\Validate
*/
abstract class FormValidtate
{
//定义一个属性存储责任链实例
protected $nextHandler;
final public function setNext(FormValidtate $formValidtate)
{
$this->nextHandler = $formValidtate;
}
final public function handle(Request $request)
{
if (!$this->handleFormCondition($request)) {
return false;
}
$this->nextHandler->handleFormCondition($request);
}
abstract public function handleFormCondition(Request $request);
}
创建两个类TestForm1、TestForm2继承自FormValidate
<?php
/**
* Created by PhpStorm.
* User: iamcyan
* Date: 2017/6/30
* Time: 13:45
*/
namespace App\Services\Validate\Form;
use App\Services\Validate\FormValidtate;
use Illuminate\Http\Request;
class TestForm1 extends FormValidtate
{
public function handleFormCondition(Request $request)
{
if ($request->get('test1') == 'test1') {
echo 'testForm1---success';
return true;
} else {
echo 'testForm1---fail';
return false;
}
}
}
<?php
/**
* Created by PhpStorm.
* User: iamcyan
* Date: 2017/6/30
* Time: 14:32
*/
namespace App\Services\Validate\Form;
use App\Services\Validate\FormValidtate;
use Illuminate\Http\Request;
class TestForm2 extends FormValidtate
{
public function handleFormCondition(Request $request)
{
if ($request->get('test2') == 'test2') {
echo 'testForm2---sucess'.PHP_EOL;
return true;
} else {
echo 'testForm2---fail';
return false;
}
}
}
在控制器中进行访问
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\Validate\Form\TestForm1;
use App\Services\Validate\Form\TestForm2;
class FormController extends Controller
{
protected $testForm1;
protected $testForm2;
public function __construct(TestForm1 $testForm1, TestForm2 $testForm2)
{
$this->testForm1 = $testForm1;
$this->testForm2 = $testForm2;
}
public function create()
{
$array = [[1,2,3], [4,5,6], [7,8,9]];
$res = array_collapse($array);
var_dump($res);
$res = array_collapse($res);
dd($res);
return view('form.index');
}
public function store(Request $request)
{
$this->testForm1->setNext($this->testForm2);
$this->testForm1->handle($request);
}
}
上面的这种写法是以一种面向对象的思维对多个验证条件进行链式验证
即 条件1:true->条件2:true->条件3:true.....。没有其他的额外的分支。
网友评论