Welcome Guest, Not a member yet? Register   Sign In
Avoid rewriting code
#1

[eluser]Unknown[/eluser]
Almost all models need a get, add, update, delete and count method. I solved this by making my own extended parent-model. But then again the rules and field-variables in the validation-class are almost the same for my edit and add-methods in the controllers (and for large forms it feels stupid to list them again just a few lines down below). And the edit- and add-views are almost also the same.

So, what's your approach to avoid writing the same code over again. Confusedmirk:
#2

[eluser]Phil Sturgeon[/eluser]
Copy and paste! :p

I find if you try and get the code to do all the development work for you, you end up with a very clunky system that wont let you do a whole bunch. Make a good model/view/form/whatever then copy and paste lots!

BUT

To give you a more useful answer, you could extend the model library and give it a set of fields and table names in the constructor.

Code:
class Blog_model extends Model {

    function Blog_model()
    {
        // Call the Model constructor
        parent::Model(array(
            'table' => 'blogs',
            'fields' => array('id', 'title', 'body', 'date')
        ));
    }
    
}

Then in make a new Model extension MY_Models.php in your application library folder that replaces the constructor and makes a bunch of default functions based on your fields.
#3

[eluser]Mirage[/eluser]
My approach is to keep things flexible. If things are 'almost' the same they're not the same. I can optimize the living daylight out of everything just to run into 'another' exception to the rule down the road.

Models, Controllers, etc are one thing. They are php classes that can be extended, overriden, sliced and diced. Validation and view contents are a bit of a different thing.

For views, if a form is different - even if ever so slightly I write the whole thing. That's in part 'defensive' coding because I know that if I don't do that, something WILL be different in the future and that'll bring down my optimizations like a house of cards.

For validation, I use configs. I keep a cfg_forms.php in my config directory in which I store named arrays depending on the form:

Code:
$config['form_signup']['fields']  =array('name'=>'Real Name', 'email'=>'Email Address', ....);
$config['form_signup']['rules']   =array('name'=>'trim', 'email'=>'trim|required|valid_email');
$config['form_signup']['messages']=array('valid_email','Your email address is not valid');

In the controller, when I need to validate a form I just load the config and pass the proper items to the validation class:
Code:
function signup() {
    $this->load->library('validation');
    if ($_SERVER['REQUEST_METHOD']=='POST') {
        $this->_prepareValidation('signup');
        if ($this->validation->run()) {
            // success proceeds from here
        }
    }
    $this->load->view('signup');
}

function _prepareValidation($form) {
    $this->load->config('cfg_forms');
    $cfg=$this->config->item("form_{$form}");
    $this->validation->set_fields($cfg['fields']);
    $this->validation->set_rules($cfg['rules']);
    $this->validation->set_message($cfg['messages']);
}

Now if your forms have overlapping fields, you could save a some lines in the config, by creating a base configuration and then extending it per form:

Code:
$config['_stdfields_']['fields']  =array('name'=>'Real Name', 'email'=>'Email Address', ....);
$config['_stdfields_']['rules']   =array('name'=>'trim', 'email'=>'trim|required|valid_email');
$config['_stdfields_']['messages']=array('valid_email','Your email address is not valid');

$config['form_signup']=$config['_stdfields_'];
$config['form_signup']['fields']['gender']=['Gender'];
...
...

Personally, I don't like the above. I'm more of an explicit guy... I already have one place to define my validation configs, so I really don't care copying and pasting parts for other forms. Too many dependencies can get in the way...

Finally you could move the _prepareValidation() function to a helper so you don't need to put it in every controller.

HTH,
-m
#4

[eluser]Flemming[/eluser]
It's really about personal preferrence I think. I have found that taking over from a coder who did EVERYTHING possible to make his code re-usable and did indeed reuse it abundantly has been very difficult as the level of abstraction became utterly incomprehensible to anyone apart from the original coder.

Re-using is of course important, but not if it makes editing difficult. Even the best planned and implemented code will need some adjustment somewhere down the line so it is important to keep this in mind when developing your reusable code.

I anticipate some criticism for saying this but I'm just speaking from experience, that there comes a point where reusable code crosses over into unusable/incomprehensible.
#5

[eluser]dpgtfc[/eluser]
[quote author="flemming" date="1223044997"]
I anticipate some criticism for saying this but I'm just speaking from experience, that there comes a point where reusable code crosses over into unusable/incomprehensible.[/quote]

I think I can agree with your point. Re-usable code is great, which is why OOP is so important, but there is a line that gets crossed on occasion when people try to abstract things out too much.
#6

[eluser]Unknown[/eluser]
I can agree with anything previously said but I think that when writing code for a particular task you end up writing boilerplate code that has nothing to do with the task to be coded, for example validation, transaction management, logging, error reporting, etc.

This is what in Aspect Oriented Programming is called crosscutting concerns and with Aspect Oriented Programming you can avoid doing that separating both tasks, but unfortunately I haven't seen any good implementation of Aspect Oriented Programming in PHP, perhaps you should check PHPAspect http://www.phpaspect.org/

That way you don't care about writting boiler plate over and over your controllers or model, you just define aspects for logging, for transaction management and validation and then you define pointcuts on where to wave those aspects, you can decide where and when those aspects are applied and you only code them once.

Thanks
Pablo
#7

[eluser]Neovive[/eluser]
For most new projects, I try to utilize frameworks that provide a built-in ORM implementation. I believe there are some ORM libraries available in the CI wiki. Although ORM libraries decrease overall site performance a bit, they significantly speed up development by eliminating the need to write code for the items you mentioned above (get, create, update, delete, etc.). You just define your data relationships, create an instance of your model and most of the database work is done for you.
#8

[eluser]bigdaddysheikh[/eluser]
I could be wrong here due to my noobish status, but I want to ask that wouldn't a CRUD system be similar to this?




Theme © iAndrew 2016 - Forum software by © MyBB