In most cases writing less code gives the developer a series of
advantages: it’s easier to maintain and extend, easier to read and
easier to debug! In this post I’m going to suggest a little CakePHP tip
that in the long run will save you a lot of coding.
Some develepers already implement this method, but I think it deserves much wider usage: I’m talking about merging model save and edit in a single controller method.
CakePHP needs very little code to save a record to the database. Models are able to automatically detect the type of query to build (INSERT vs UPDATE) based on the type of data passed to the save() method. The difference is that when creating a new row you will not pass a record ID, which is required to UPDATE. So, using CakePHP it’s really easy to implement a unique method to do both things. Here is the controller code.
Some develepers already implement this method, but I think it deserves much wider usage: I’m talking about merging model save and edit in a single controller method.
CakePHP needs very little code to save a record to the database. Models are able to automatically detect the type of query to build (INSERT vs UPDATE) based on the type of data passed to the save() method. The difference is that when creating a new row you will not pass a record ID, which is required to UPDATE. So, using CakePHP it’s really easy to implement a unique method to do both things. Here is the controller code.
public
function
save(
$id
= null) {
// check if the form has been posted
if
(
$this
->request->is(
'post'
)) {
// try to validate and save
if
(
$this
->Model->save(
$this
->request->data)) {
$this
->Session->setFlash(
'Model Saved!'
);
$this
->redirect(
'/models/index'
);
}
}
// if an id has been passed, send record data to the view
if
(
$id
) {
$this
->set(
'model'
,
$this
->Model->findById(
$id
));
}
}
Of course you will also merge the view files, and that’s cool when
you’re managing a lot of fields. Just remember to supply the ID field
(it won’t be displayed to the user), so Cake knows when you are
performing an UPDATE query.
echo
$this
->Form->input(
'id'
);
This is today’s tip, I hope it will help you write better code!
Very cool! tks man
ReplyDelete