1) First check our directory structure
2) Use normal writing to construct our verification
This is mainly divided into four steps. Compared with using independent validators or data verification one by one, most of the code has been optimized. However, when using it, we will find that we have multiple problems. When verifying or multiple modules, there will be repetitive redundancy in writing this string of code
Question? How to compress the appeal code into one line
AOP : A technology that dynamically and uniformly adds functions to a program without modifying the source code. AOP is actually a continuation of the GoF design pattern. The design pattern tirelessly pursues the decoupling between the caller and the callee, improving the flexibility and scalability of the code. AOP can be said to be a realization of this goal## Although #AOP and OOP are very similar literally, they are two design ideas for different fields. OOP (Object-Oriented Programming) abstractly encapsulates the entities of the business processing process and their attributes and behaviors to obtain a clearer and more efficient division of logical units.We introduced the idea of aop programming to solve our problems by merging and unifying modules with a single functionWe created
validate# under common
## directory, and create a BaseValidate
file, inherit think\validate
<?php namespace app\common\validate; use app\common\controller\Base; use think\Request; use think\Validate; class BaseValidate extends Validate { /** * 基础类控制器 * @param null|array $data * @return bool */ public function goCheck($data = null) { # 当 data 不存在的时候去自动校验获取到的参数 if( is_null($data) ) { # 获取待验证的参数 $data = Request::instance()->param(); } # 进行验证 if( !$this->check($data) ) { (new Base())->ajaxjson(Base::error, $this->getError()); # 抛出的自定义异常 } return true; }
Copy after loginafter optimization Code
I feel a lot more comfortable instantly. It saves a lot of code, because this thing can be used under many controllers. It should be used
Optimization 2
For example, in the code in baseValidate, there is a string of codes is_null, which is written to verify all the data passed up. When we need to verify When verifying all the data, you only need to write like this
##The data can also be verified. But there will be a doubt. We did not get the data data. We cannot use the data data. We still need to get it again in the controller. This is not advisable, so I chose to do this