• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Set Rules in model.

#1
This is the code I have made so far.
It works but the whole if/check slug thing is ugly and I don't think it meets decent coding practices.
I don't want any check functions inside the controller. I want all check functions inside my model.
Is this the only way to make it possible?

As I've wrote this I've thought about adding a function called "function check slug()" and then call it as $this->pages_model->check_slug();

Anyways, I'd appreciate your feedback nether the less.

PHP Code:
<?php    

class Pages_model extends MY_Model {
    
    protected 
$_table_name 'pages';
    protected 
$_primary_key 'page_id';
    protected 
$_primary_filter 'intval';
    protected 
$_order_by '';
    protected 
$_rules = array();
    protected 
$_timestamps FALSE;

    public function 
set_rules($method$slug_check false)
    {
        if(
$method === 'edit')
        {
            
$id $this->input->post('page_id');
            
$slug $this->input->post('slug');
            
            
$page $this->pages_model->get_by(array('page_id' => $id), TRUE);
            
$check get_object_vars($page)['slug'];
            
            if(
$check !== $slug)
            {
                
$slug_check '|is_unique[pages.slug]';
            }            
        }

        
$config = array(
            
'add' => array(
                array(
                    
'field' => 'title'
                    
'label' => 'Title'
                    
'rules' => 'trim|min_length[5]|required|xss_clean'
                
),
                array(
                    
'field' => 'slug'
                    
'label' => 'Slug'
                    
'rules' => 'trim|min_length[5]|alpha_dash|required|xss_clean|is_unique[pages.slug]',
                ),
                array(
                    
'field' => 'order'
                    
'label' => 'Order'
                    
'rules' => 'trim|numeric|required|xss_clean'
                
),
                array(
                    
'field' => 'body'
                    
'label' => 'Body'
                    
'rules' => 'trim|min_length[5]|required|xss_clean'
                
)
            ),
            
'edit' => array(
                array(
                    
'field' => 'title'
                    
'label' => 'Title'
                    
'rules' => 'trim|min_length[5]|required|xss_clean'
                
),
                array(
                    
'field' => 'slug'
                    
'label' => 'Slug'
                    
'rules' => 'trim|min_length[5]|alpha_dash|required|xss_clean'.$slug_check.'',
                ),
                array(
                    
'field' => 'order'
                    
'label' => 'Order'
                    
'rules' => 'trim|numeric|required|xss_clean'
                
),
                array(
                    
'field' => 'body'
                    
'label' => 'Body'
                    
'rules' => 'trim|min_length[5]|required|xss_clean'
                
)
            ),
        );
        
$this->form_validation->set_rules($config[$method]);
    }

Reply

#2
It might be better to create a new unique rule which allows you to check whether any value returned from the database with the same value shares the ID of the record being validated. Then you could use the built-in is_unique rule for inserts and use the new rule for updates. It's also likely that you will need the same functionality again in the future, so the extra time it might take to build (or find) a validation function that handles it properly will be worthwhile.

Bonfire has a form validation function named unique() which serves that purpose fairly well, though it requires the field name in the form to match the name in the database table for the ID. The function was originally adapted from this article: http://code.tutsplus.com/tutorials/6-cod...--net-8308
Reply

#3
Something I've been playing with recently is schema exploring, I've only spent about an hour on this but this is what I have so far: https://github.com/monsterlane/codeignit..._Model.php

You can detect type/non-null and provide defaults or validation using those or comments. All you have to define is the table name in your model and provide hints in your schema for the rest.
Reply

#4
Doing validation in Models as well as taking input->post values in model is ugly thing. All validation and input->post should be in controller only. Second developer might feel uncomfortable in working your style of code.
Reply

#5
I'm the CTO for my company so I set the rules Smile Typically this won't be used for a lot of custom code only for basic actions. Validation would be done in controllers using a method from the model to get the required fields (via schema), then once the request is validated it would be passed unmodified to the model where it extracts the relevant keys, hooks modify, and insert/update the data.
Reply

#6
While I would avoid using $this->input->post() in my models where possible, validation rules are largely determined by the structure of your database, so there are only a small number of reasons that any validation rules should reside in the controller.

Because the form_validation library makes it simple to perform validation and make the results of that validation available to the view, I usually load the library from my controller and run the validation there, but I store the rules in my model and only allow the controller to define validation rules which are specific to the controller's action. Bonfire does have a method in its base model which allows you to validate insert and update calls within the model, I just usually prefer to setup the extra steps in my controller in case I need some controller-specific validation.

I also use a prep_data() method in my model (also supported in the Bonfire base model) which accepts an array (the controller calls $this->input->post() and may or may not modify the data before passing it to the model's method) and allows me to ensure default values and other requirements are fulfilled as well as ignoring/removing data which is not related to the model.

For example:
PHP Code:
class Ticket extends Admin_Controller
{
 
   // ...

 
   private function saveTicket($type 'insert'$id 0)
 
   {
 
       // Optionally, the result of get_validation_rules() can be 
 
       // assigned to a variable and modified before being passed to
 
       // set_rules().
 
       $this->form_validation->set_rules($this->tickets_model->get_validation_rules());
 
       if ($this->form_validation->run() === false) {
 
           return false;
 
       }

 
       // Optionally, the result of $this->input->post() can be 
 
       // assigned to a variable and modified before being passed to
 
       // prep_data().
 
       $data $this->tickets_model->prep_data($this->input->post());

 
       if ($type == 'insert') {
 
           $id $this->tickets_model->insert($data);
 
           if (is_numeric($id)) {
 
               return $id;
 
           }
 
       } elseif ($type == 'update') {
 
           $ticketKey $this->tickets_model->get_key();
 
           $data[$ticketKey] = $id;
 
           return $this->tickets_model->update($id$data);
 
       }

 
       return false;
 
   }

 
   // ...



Some developers can find this kind of back-and-forth between the controller and model during handling of view data awkward, but it is primarily intended to make it easier to maintain the site in the long-term and allows the same level of flexibility while ensuring that maintainability. In many cases, I've seen situations in which developers were expected to use and understand frameworks with greater levels of separation and abstraction than this.
Reply

#7
i like my controllers thin and commanding :-)
here's one of my reasons - almost always after a form validation - you are going to insert or update to a database.
so you are going to have a model with all of the relevant field names to do that. having the form validation in the same model,
or close by, makes it much easier to match the validation requirements with the database needs.

another possibility is doing the form setup and validation with configs which is how i started - i think there are some nettuts courses that taught me ths -- but its easier to call a model and again you can have relevant code together.

the other reason is that when code is touched, it can break. by keeping all those ever changing form details out of the controller,
much more likely to not break it. if there is a problem in a model method it (probably) will not take down
every single method in the controller.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.