phalcon 利用注解实现验证

阅读更多
phalcon 利用注解实现验证

为了精简验证参数的代码,做如下处理。(对Laravel 5 来说,这个功能是现成的,phalcon的话,需手工处理一下)

在注册服务时:

// 验证器事件。$di是FactoryDefault 对象。
$my_eventsManager = new EventsManager();
$my_eventsManager->attach( 'dispatch',new Annotation() );

$di->get("dispatcher")->setEventsManager($my_eventsManager);

主要代码:

namespace Apps\Validations;

use Apps\Exceptions\InvalidRequestException;
use Phalcon\Events\Event;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\User\Plugin;

/**
* 利用 注解 实现控制器请求参数验证。
*
*/
class Annotation extends Plugin
{
    /**
     * This event is executed before every route is executed in the dispatcher
     */
    public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
    {
        // Parse the annotations in the method currently executed
        $annotations = $this->annotations->getMethod(
            $dispatcher->getControllerClass(),
            $dispatcher->getActiveMethod()
        );

        // Check if the method has an annotation 'Validation'
        if ($annotations->has('Validation')) {
            $annotation = $annotations->get('Validation');
            $class =trim($annotation->getNamedParameter('class'));
            $validation = new $class;
            $messages = $validation->validate($this->request->get());

            if (count($messages)) {
                foreach ($messages as $message) {
                    throw new InvalidRequestException($message);
                }
            }
        }
    }
}

异常代码

namespace Apps\Exceptions;

use Exception;


class InvalidRequestException extends Exception
{
    public function __construct(string $message = "", int $code = 400)
    {
        parent::__construct($message, $code);
    }
}

修改 public/index.php
try{
    /**
     * 定义项目目录
     */
    define('ROOT_PATH', dirname(__DIR__).'/');
    define('APPS_PATH', ROOT_PATH . 'apps/');

    $di = new \Phalcon\DI\FactoryDefault();
    require CONFIG_PATH . 'services.php';
    $application = new Application();
    $application->setDI($di);
    require CONFIG_PATH . 'modules.php';
    require  CONFIG_PATH . 'router.php';
    echo $application->handle()->getContent();
}catch(\Phalcon\Exception $e){
    echo "phalcon err";
}catch(\Apps\Exceptions\InvalidRequestException $e){
    echo "请求参数错误啦:".$e->getMessage();die;
}catch(PDOException $e){
    echo "err";
}


使用示例,带注解的方法:

namespace Apps\Api\Controllers;

use Apps\Common\Controllers\ControllerBase;

class TestValidateController extends ControllerBase
{
    /**
     * 这是一个测试用方法
     *
     * @Validation( class = "\Apps\Validations\TestValidation" )
     */
    public function indexAction()
    {
        echo "all ok4";
    }
}

使用示例:控制器验证,验证请求中一定有aa这个参数。
namespace Apps\Validations;

use Phalcon\Validation;
use Phalcon\Validation\Validator\Email;
use Phalcon\Validation\Validator\PresenceOf;

class TestValidation extends Validation
{
    public function initialize()
    {
         $this->add(
            'aa',
            new PresenceOf(
                [
                    'message' => 'aa必须有。',
                ]
            )
        );

    }
}




你可能感兴趣的:(phalcon,注解,验证)