Tannin
Tannin

Reputation: 65

mysqli: mixing OO and procedural code

The php manual mysqli page discusses mixing object oriented and procedural styles, saying that "mixing both styles is not recommended for code clarity and coding style reasons."

I maintain and update a largish project (many thousands of code lines) which is around 10 years old now, and will go on for at least that many more. (Regard it as a sort of image CMS if you like.) All of the existing mysqli code is in procedural style, much of it little changed from the old mysql extension it used originally. (And still perfectly functional in most cases.) Project code modules get updated, added, removed and/or replaced on a rolling as-required basis, so I'll be doing sporadic work on this project for many years yet.

I want to switch it over to OO style for clarity, brevity, and maintainability. Unlike the change from mysql to mysqli, this is not something that can be easily done with just a little thought and a lot of global search/replace. Changing the whole project in one go is not an attractive option. It's probably most time-efficient to simply live with procedural mysqli forevermore, but I don't mind putting the work in to make it better, just so long as I don't have to do it all at once.

Is it practical to change only part of the project, leaving other parts in procedural style until such time as they are due for a re-write anyway?

What are the gotchas here? What things can be mixed freely and what things cannot when you combine OO and procedural mysqli?

Edit: for clarity, I am not asking about broad-ranging stylistic matters, purely for the specifics of mixing OO-style and procedural style calls to the mysqli extension. The manual contains nothing except a bland statement that "it is possible to switch between styles at any time" without giving any useful detail.

Upvotes: 3

Views: 421

Answers (1)

Dharman
Dharman

Reputation: 33373

There is nothing wrong with mixing OO and procedural styles. Just as the citation says it is 'not recommended for code clarity and coding style reasons'.

However, if all you did when migrating from mysql_* to mysqli_* was global search and replace just to change the name of the functions then you have really missed the whole point of the new API.

The idea is that when migrating you should implement prepared statements and clean up the messy spaghetti code that mysql_* functions often were a culprit of. Sticking with procedural style provides you no benefit at all and even complicates the code more. Prepared statements and exceptions are much cleaner when used in OO style.

If you are not using parameter binding and mysqli exceptions you might as well stick to using mysql_* functions.

Upvotes: 3

Related Questions