Kohana 3: Example of model with validation

后端 未结 4 1229

I find examples and tutorials about models and about validation. And I places that say the validation (or most of it at least) should be in the model, which I agree with. But I

4条回答
  •  有刺的猬
    2021-01-30 04:51

    An example of KO3 validation used with ORM models. Example was posted with permission by a1986 (blaa) in #kohana (freenode).

     array());
    
      protected $_rules = array(
        'document' => array(
          'Upload::valid'     => NULL,
          'Upload::not_empty' => NULL,
          'Upload::type'      => array(array('pdf', 'doc', 'odt')),
          'Upload::size'      => array('10M')
        )
      );
    
      protected $_ignored_columns = array('document');
    
    
      /**
       * Overwriting the ORM::save() method
       * 
       * Move the uploaded file and save it to the database in the case of success
       * A Log message will be writed if the Upload::save fails to move the uploaded file
       * 
       */
      public function save()
      {
        $user_id = Auth::instance()->get_user()->id;
        $file = Upload::save($this->document, NULL, 'upload/contracts/');
    
        if (FALSE !== $file)
        {
          $this->sent_on = date('Y-m-d H:i:s');
          $this->filename = $this->document['name'];
          $this->stored_filename = $file;
          $this->user_id = $user_id;
        } 
        else 
        {
          Kohana::$log->add('error', 'Não foi possível salvar o arquivo. A gravação da linha no banco de dados foi abortada.');
        }
    
        return parent::save();
    
      }
    
      /**
       * Overwriting the ORM::delete() method
       * 
       * Delete the database register if the file was deleted 
       * 
       * If not, record a Log message and return FALSE
       * 
       */
      public function delete($id = NULL)
      {
    
        if (unlink($this->stored_filename))
        {
          return parent::delete($id);
        }
    
        Kohana::$log->add('error', 'Não foi possível deletar o arquivo do sistema. O registro foi mantido no banco de dados.');
        return FALSE;
      }
    }
    

提交回复
热议问题