I’m writing an application in CakePHP that, for now, is to be used to make quotes for customers. So Quote is a model. I want to have a separate model/table for something like “Property,” which may be used by other models.
Each time a user gets to the “Add Quote” action, I basically want to pull a Property called “nextQuoteNumber” or something along those lines, and then automatically increment that property, even if the new Quote isn’t saved. So I don’t think just using an autoincrement for Quote’s id is appropriate here – also, the “quote number” could be different from the row’s id.
I know this is simple enough to do, but I’m trying to figure out the “proper” CakePHP way of doing it! I’m thinking that I should have a method inside the Property model, say “getProperty($property_name)”, which would pull the value to return, and also increment the value… but I’m not sure what the best way of doing that is, or how to invoke this method from the Quotes controller.
What should I do? Thanks in advance!
I ended up doing something a bit more specific, making a model for ‘Sequence’ rather than the more general ‘Property’. Sequence has three fields: id, name, value. Since I currently need a sequence for quotes starting from 1001, there’s one row (1, ‘Quote’, 1001).
In the model file sequence.php is the following:
As webbiedave pointed out, atomicity is required or it’s possible that two users/quotes could get the same sequence number, hence the begin() and commit() calls.
Then, in my quotes_controller, I added the following in the add() action:
Then I can use the $quoteNumber as I wish.
Hope this helps somebody, and please contribute if there’s a better way of doing it. Thanks!