Welcome Guest, Not a member yet? Register   Sign In
Describing database structure
#1

[eluser]donald.tbd[/eluser]
Hello,

In my previous framework i used to describe my database structure in the model, that would help my with validation, inserting, form generation and such. I also tried it in CI.

Here is what it looks like:

For example i have a table that holds forum thread posts.
In my model i will have:
Code:
$this->set_structure(
  array(
    "user_id" => array(
      "field" => "user_id",
      "label" => "user_id",
      "rules" => "required"
    ),
    "title" => array(
      "field" => "title",
      "label" => "title",
      "rules" => "required"
    ),
    "content" => array(
      "field" => "content",
      "label" => "content",
      "rules" => ""
    )
  )
);

Now, the first thing this is helpful with is validation. In my controller i use it like this:

Code:
$this->form_validation->set_rules($this->model->get_structure());
$this->form_validation->run()

I could also put the same thing into config file and access it a bit faster but to me it seems that its more apropriate in the model file cos it basicly is the descrpition of the table i am using.
Also, a big pluss in this case is that if i havent worked on a project for a while and have forgotten the db structure then i can just see it in the beginning of every model file and i know exactly what i am working with.

The other thing i use it for is inserting data. For example if i submit a form then there might be some unneeded data there (submit, maybe even some user added fields in hacking purposes or something like that)

Basicly what i do is just before inserting data i pass it on through a function that looks like this:

Code:
function populate_structure($input){
  $output = array();
  foreach($input as $key => $value){
    if(array_key_exists($key, $this->get_structure())){
      $output[$key] = $value;
    }
  }
  return $output;    
}

This way i get rid of all unneeded fields and i can be sure that the array i am giving to insert function of CI is pretty much safe.

And for last this could also be used very well for generating forms. I havent gotten to that part yet but it is possible! Smile

Thats pretty much it. What i would like to know is if anyone else is using this kind of logic? Maybe give some new suggestions how to make it better / even more comfortable. Or just tell me what you think about this idea, whats good/bad about it, so i can make it better.

Thanks! Smile
#2

[eluser]Nick_MyShuitings[/eluser]
I do something similar with my crud code. One array is used for frontend, backend, and model validation, and is used to build the form. I think its a good idea, but to each his own.




Theme © iAndrew 2016 - Forum software by © MyBB