dongtiaobeng7901 2015-07-30 16:49
浏览 82
已采纳

变量到另一个php文件

I have a php file(register.php) with a public function register($data) where errors are validated.Then errors are counted and if no errors are found, validation is passed.

register.php:

class ARegister {

    public function register($data) {
      $user = $data['userData'];

      //validate provided data
      $errors = $this->validateUser($data);

        if(count($errors) == 0) {
        //first validation
        }
    }

    public function validateUser($data, $botProtection = true) {

    $id     = $data['fieldId'];
    $user   = $data['userData'];
    $errors = array();
    $validator = new AValidator();

       if( $validator->isEmpty($user['password']) )

            $errors[] = array( 
            "id"    => $id['password'],
            "msg"   => Lang::get('password_required')
             );


      return $errors;
   }

The problem is, that I need to get this confirmation of validated data to my other php file (othervalidation.php) where I've made another validation:

othervalidation.php:

<?php
require 'register.php';

if ( !empty($action) ) {

     switch ( $action ) {

        case 'process_payment':

        try {  

            $instance = new ARegister();

            if($instance->validateUser($data, $errors)) {
            throw new Exception('Validation error');    
            }

        }   catch (Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
     }

How can I send the result of $errors variable to my other validation (othervalidation.php)?

  • 写回答

2条回答 默认 最新

  • dsa122870 2015-08-01 12:00
    关注

    I looked at your new code design and here's the new problems I found.

    First, in your register function, you use the errors variable as an integer while your validate function returns an array. You got two possibilities here.

    You can change your register method to check out if your error array is empty like this:

    if(empty($errors)) {
            //first validation
    }
    

    Count is also valid, but I still prefer empty since it's syntactically clearer. Furthermore, the count function returns 1 if the parameter is not an array or a countable object or 0 if the parameter is NULL. As I said, it is a functional solution in your current case but, in some other contexts, it might cause you unexpected results.

    Here in your method declaration, I see that you are expecting a boolean (botProtection).

    public function validateUser($data, $botProtection = true) {
    

    But you are supplying an errors parameter

    if($instance->validateUser($data, $errors)) {
    

    You don't provide me the declaration of the errors variable, but it is probably not matching the bot protection parameter your function is expecting. PHP is using lose typing, it is useful but, once again, you got to be careful for bugs hard to find. For public function, you should always make sure a way or another that the supplied parameter won't lead to code crash.

    In your code, the data parameter seems to be an array. You can use parameter hinting to force the use of array like this:

    public function register(array $data) {
    public function validateUser(array $data, $botProtection = true) {
    

    And even specific class (as if you where using "instance of" in a condition)

    public function register(MyDataClass $data) {
    public function validateUser(MyDataClass $data, $botProtection = true) {
    

    Also, you're not even using the botProtection parameter in your validateUser method.

    On the same function call:

    if($instance->validateUser($data, $errors)) {
    

    you are expecting a Boolean (true or false), but the method returns an array. If you want to use the code the way it is currently designed, you must use it like this

    if(!empty($instance->validateUser($data, $errors)) {
    

    Here, I'm not so sure it is necessary to use exception. Ain't it be easier to design your code like this?

    if(!empty($instance->validateUser($data, $errors)) {
    
            $message = 'Validation error';   
    }
    

    In your validate function, is the "isEmpty" function also validating if the client provided a password?

    If that's the case you could validate it like this:

    if(!in_array($user['password']) or empty($user['password']))
    

    With those corrections, your code should be functional.

    Here's a sample of how I would had design your code (considering the code sample provided):

    class ARegister {
    
        public function register($data) {
    
          $user = $data['userData']; //don't declare it here, all the user validations must be done in validateUser($data, &$errors)
    
          $errors = array();
    
          if($this->validateUser($data, $errors)) {
            //first validation
           }
        }
    
    
        /**
        * Note: If you are not returing more than one error at the time, $errors should be a string instead of an array.
        */
        public function validateUser($data, array &$errors) {
    
            $isValid = false;
    
           if (in_array($data['fieldId']) and in_array($data['fieldId']['password']) and in_array($data['userData'])){
    
               if(!in_array($data['userData']['password']) or empty($data['userData']['password'])){
    
                    $errors[$data['fieldId']['password']] = Lang::get('password_required');
                }
                else{
                    $isValid = true;
                 }
    }       
            else{
    
                //an invalid data array had been provided
            }
    
          return $isValid;
       }
    

    For the next part, if the code is executed directly in the view and you are a beginner, create a procedural external controller file (all functions will be public...). If you are a professional, you MUST create a class to encapsulate the treatment.

    You must not do treatment directly in the view. The view is a dumb placeholder for data presentation and collecting client's input. The sole action it must do is display the data sent by the controller and send back the client's input to the controller.

    The treatment on data is the controller responsibility.

    if (!empty($action) ) {
    
             $errors =array();
    
             switch ( $action ) {
    
                case 'process_payment':
    
                    $instance = new ARegister();
    
                    if($instance->validateUser($data, $errors)) {
    
                        //the user is valid, do the treatment
                    }
                    else
    
                        PageManager::dispayError($errors);
                    }
    
                    unset($instance);
             }
        }
    

    Here's an example how you can centralize your error display

    /**
         * Can be more complexe than that, but I'm at my father's home at four hundred kms away from Montreal right now..
         */
         public static function dispayError($errors, $size = 4){
    
             if (is_numeric($size)){
    
                 if ($size < 0){
                     $size = 1;
                 }
                 elseif($size > 5){
                     $size = 5;
                 } 
             }
             else{
                 $size = 4;
             }
    
             if (is_scalar($errors)){
    
                 echo '<h' . $size . 'class="ERROR_MESSAGE">' . $errors . '</h' . $size . '><br>';
             }
             elseif (is_array($errors)){
    
                foreach ($errors as $error){
    
                    if (is_scalar($error)){
    
                        echo '<h' . $size . 'class="ERROR_MESSAGE">' . $error . '</h' . $size . '><br>';
                    }
                }
             }
         }
    

    Of course, you can also support many kind of message:

    public static function dispayError($errors, $size = 4){
    
        self::displayMessage("ERROR_MESSAGE", $errors, $size=4);
    }
    
    private static displayMessage($class, $messages, $size=4)
    

    Well, took me two hours to write that. I hope you have now enough material to build an efficient, reusable and, no less important, safe code design.

    Good success,

    Jonathan Parent-Lévesque from Montreal

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式