I have a project that uses the underscore naming convention for the MySQL database and PHP scripts but uses camelCase for the javascript application (a common scenario I’m sure).
However, once JSON encoded objects are sent from the server-side to the client-side the javascript naming convention gets polluted with objects that have properties using the underscore naming convention!
The mismatch becomes apparent, for example, when a JSON object property is directly compared with a local variable e.g.
function matchCustomerByName(customer, firstName, lastName){
if (customer.first_name === firstName && customer.last_name === lastName) {
...
}
}
Maybe its just me but I don’t like the above naming style mismatch. My question is are they any standard/preferred/accepted ways of resolving the issue? Is it even an issue?
I’m tempted to use camelCase across the entire project (MySQL, PHP and javascript). The above function would then read:
function matchCustomerByName(customer, firstName, lastName){
if (customer.firstName === firstName && customer.lastName === lastName) {
...
}
}
However, using camelCase for the MySQL database seems to go against common practice.
Perhaps I could convert between the two naming conventions at the PHP stage? Is there an easy (error proof) way of doing this?
1
You should assume that the server-side dataobjects use their own conventions, and the client-side would have its own. When fetching/posting data, you can set up a model adapter to handle switching between the two. By doing it at this level, each side uses their own conventions that make sense in each’s contexts.
After fetching your data from an ajax get, or whatever, you can pass it to an adapter function like so:
function adaptCustomerFromGET(json) {
return {
firstName: json.first_name,
lastName: json.last_name,
...
};
}
function adaptCustomerForPOST(model) {
return {
first_name: model.firstName,
last_name: model.lastName,
...
};
}
Sure, it’s another place to have to update when your model changes, but it’s incredibly common to do this kind of thing, since whatever server-side API you’re connecting to may have use very different conventions than you’d need client side, including the structure of the data itself; you may be getting a list from the server that you prefer to build a map out of for work client-side.