Is It Acceptable to Use a Mix of Object Oriented Style with Procedural Style in Coding PHP

Is it acceptable to use a mix of object oriented style with procedural style in coding PHP?

While how you code is entirely your decision and unique style, I'd say there are a few factors to consider when deciding on procedural, object oriented, or mixed.

Program specifications -

Primarily, if you are on a team, writing the program for someone else, or following your own specifications, consider whether or not the choice has already been made.

Availability -

Let's face it. Sometimes the best libraries are available in either object oriented or procedural, and not both. In such a case, changing from one style would require using a completely different library, or building a class or function library yourself. An available library may save you time, with the only offset cost being a procedural function in a primarily object oriented program, or vice versa.

Familiarity -

Similar to availability, you may be more familiar with a certain class or set of functions. While you may have time to stop and learn a new class module to add to your knowledge, you may be able to save time by using a procedural library that you've already learned and thoroughly tested. So if you are working on a timeline, you may want to go with the more familiar library. However, if you are researching and learning, then you may want to take the time to read documentation, install, and test a new solution.

Data handling and speed -

One more factor to muse about is how are you handling the data. If the data is within the class, then the class will likely have methods to operate on the data. In such a situation, procedural programming would require obtaining the data from the class or object, operating on the data, and then updating the object. A better design would be to include the function in the object in my opinion.

However, if all of your data handling is outside of the class, then using a function may be faster. If you wanted to use a class method, you would have to load the class, and possibly create an object. Even static methods may be slower than a function. So if speed is a consideration, such as in a loop, then consider how many steps your program and PHP has to go through to get to the function, class, or object.

Looking ahead -

If you are wanting to select between procedural or object-oriented programming, then try to predict what will be most useful in the future. I've found object-oriented programming to be very useful for creating reusable code. I've found procedural programming to be very useful for command line code and organizing and using objects. It's likely these will stay the same as computer science evolves, and so work I've done previously is more likely to be useful again.

In contrast, some libraries and programming languages may encourage a style. PHP supports both styles. But if my overall impression is accurate, then PHP has been moving in the direction of object-oriented styles. If selecting between PHP functions and objects, look and see what version of PHP the functions were created for. Also check to see if any of the procedural functions are depreciated or going to become obsolete. If so, use the object-oriented approach, as this will make your program more useful when those procedural functions are no longer supported.

Hope this provides some considerations. Thanks.

procedural style and object oriented style

famous for not knowing how to asking questions

Sad but true.

If some of your code is not working, it's better to post this very code instead of writing a long literary explanation.

When you're making it

while ($rowinfo = mysqli_fetch_assoc($object->query($sql)))

it indeed makes an infinite loop, because you are making your SQL query run over and over.

The problem has nothing to do with object syntax, it will remain the same with procedural as well. You are just supposed to use the result in stead of calling query again.

In essence, you have to run your query **only once. **

Which makes your other code snippet wrong as well. It should be

$object = new mysqli('localhost', 'readmode', 'p@5sW0rd', 'practices');
$sql = 'SELECT * FROM paintings';
$result = $object->query($sql);
if ($object->connect_error) {
$error = $object->connect_error;
} else {
$num_rows = mysqli_num_rows($result);
}

otherwise it will run your query twice.

Architecting a PHP application from procedural to Object Oriented

Pick any of major PHP frameworks ZendFramework, Symfony, Silex, Slim ... and build your CMS on those. Those framework already have most of components you need. Plus they have big communities behind, so you will not have to maintain that code.

If you still want to write your own framework. Take a look in to http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller for Handling requests.
No need to create DB classes as PDO http://php.net/manual/en/book.pdo.php is a nice built in abstraction layer you can use.

PHP vs OO PHP - Which one to use?

The real advantage of object-orientation: your code is better organized, easier to maintain, more modular (and thus easier to reuse), and potentially less brittle (because of encapsulation of state and implementation, and hopefully better security). (The cynic in me also says that if you learn object-oriented PHP, you take the first important step to leaving the PHP ghetto. Heh. Worked for me!)

There's already a lot of questions from PHPers moving into OO on Stack Overflow:

  • PHP Object Oriented or Not?
  • Is my PHP code object oriented?
  • Learning PHP Class

Not to mention that there are zillions of PHP object-oriented tutorials out there. My take: basically, yes, if you are writing PHP, you should probably be writing object-oriented PHP for anything beyond the most trivial of applications. There are lots of Rails-like frameworks for PHP that will make your life easier, and may help you become a better programmer.

simple explanation PHP OOP vs Procedural?

Background: You asked for a "simple explanation" which suggests:

  1. You want a no-nonsense overview without jargon
  2. You want something that will help you learn from the beginning
  3. You have discovered that no two people ever answer the question the same way, and it's confusing. That's the reason you are here asking for a simple explanation. Yes?

Short No-Jargon Answer:

  1. Many introductory explanations jump quickly into "OOP real world" examples. Those can tend to confuse more than help, so feel free to ignore that for now.
  2. You can think of source code simply as "chunks" of functionality, that just happen to be saved to individual files.
  3. There are different ways of organizing those "chunks"; depending on things like conventions of the programming language, the background and training of the developer(s), or just plain old personal preference.
  4. OOP and Procedural programming are simply two main, generally-recognized methodologies, for how to organize and arrange those "chunks" of code.

Long No-Jargon Answer:

Procedural vs OOP is just one aspect of a fundamental issue of computer programming: how to make your code easy to understand and a piece of cake to professionally maintain. You can actually write "Procedural" code that follows some of the principles of OOP, so the two are not necessarily opposites.

Your understanding will really grow once you learn other object-oriented programming languages, among which, PHP is a "new kid on the block".

Here is a quick overview of what you will learn as you build experience:

  • You can write PHP source code that does useful tasks

  • You can organize useful tasks into "chunks" of code

  • You can think of "chunks" of code independently of the individual files where they are saved

  • Sometimes those "chunks" of code will behave differently based on parameters you pass in

  • Chunks of code that accept parameters are called "Functions"

  • Functions can be "chunked" together, and there are different ways of doing this:

    • For example: you could have just one big PHP file with all the functions you have ever written in your entire life, listed in alphabetical order by function name
    • For example: you could have multiple PHP files with functions that are chunked together by subject matter [e.g., functions for doing basic string manipulation, functions for processing arrays, functions for file input/output, etc]
  • OOP is a special way of "chunking" Functions together into a "Class"

  • A Class is just another level of "chunking" code together so that you can treat it as a unified whole

  • A Class can be thought of as a "chunking" of methods and properties

    • methods are simply functions that are logically related to one another in some meaningful way. The words "method" and "function" are basically two different terms for the same thing.
    • properties are simply data values that are related to the class. These are values that are intentionally non-isolated to any individual function, because more than one of the functions in the class should have access to them.
      • For example: if your class has a bunch of methods for doing astronomy, properties of the class might be the values for certain famous numbers that all astronomy methods need to know about (like Pi, the speed of light, the distance between specific planets, etc.).
    • This is where most OOP explanations get confusing because they branch off into "real world examples" which can quickly get off-topic. Often, "real world" is a euphemism for the ontological perspectives of a particular individual or group. That tends to be useful only once you already understand the concept well enough to teach it to someone else.
    • To understand OOP without confusion, you can skip the "real world" examples for now, and just focus on the code. A Class is simply a way to store functions (aka methods) and properties (aka data) as PHP code in one or more related "chunks" where each individual "chunk" deals with a specific topic or piece of functionality. That's all you need to know in order to get started.
  • A Class is useful because it allows you to organize your code at a very high level in a way that makes it easy for you to understand, use, and maintain.

  • When someone has written a lot of functions, and organized them into a lot of Classes, and gotten those to work together in some cool way, they package the whole thing together and call it a "Framework".

  • A Framework is just the next-highest level of "chunking" (including coding style and conventions) that one or more people agree on because they like the way the code is organized and it suits their working style, preferences, values, plans for world domination, etc.

See also

  • OOP appeal

Classes. What's the point?

Classes are a notion of object-oriented design (and programming and analysis, respectively), where they are used to encapsulate data and methods.

Other object-oriented programming techniques may include features such as

  • information hiding,
  • data abstraction,
  • encapsulation,
  • modularity,
  • polymorphism and
  • inheritance

From an article .. top-15-best-practices-for-writing-super-readable-code:

Object oriented programming can help you create well structured code. But that does not mean you need to abandon procedural programming completely. Actually creating a mix of both styles can be good.

From http://java.sun.com/docs/books/tutorial/java/concepts/class.html:

In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.

Finally, a short youtube video about the differences between the procedural and object-oriented programming paradigm ...

PHP includes vs OOP

These are not really opposite choices. You will have to include the checking code anyway. I read your question as procedural programming vs. OO programming.

Writing a few lines of code, or a function, and including it in your page header was how things were done in PHP3 or PHP4. It's simple, it works (that's how we did it in osCommerce, for example, an eCommerce PHP application).

But it's not easy to maintain and modify, as many developers can confirm.

In PHP5 you'd write a user object which will carry its own data and methods for authentication. Your code will be clearer and easier to maintain as everything having to do with users and authentication will be concentrated in a single place.



Related Topics



Leave a reply



Submit