Is it some bizarre heresy to use classes without objects? - php

This may be a silly question, but it's been bugging me.
I've been writing what I believe to be procedural code, but I'm using classes which group together related public and private functions according to purpose. Instead of using objects and methods, I call the functions when needed with a scope resolution operator. ie: db::execute($sql)
I know it's ridiculous, but I just now realized everyone immediately associates classes with OOP. Am I committing some perverted heresy?

you're basically abusing one language construct (class) to emulate another one (namespace). This is totally normal, as long as you use a language that doesn't support the latter (php 5.2-).

If you know the distinction between classes and "OOP use of classes" then I guess it is not a real problem ...

"Perverted heresy" might be taking it a little far, but you're certainly missing out on much of the organizational power of object oriented programming.

It sounds to me like you're using classes as namespaces.
I don't see anything particularly wrong with this - it provides logical separation of concerns, and presumably makes things easier for you to develop/maintain.
You'd definitely be better off learning more about Object-Oriented Programming so you can take advantage of the benefits it offers.

As long as you don't claim to be doing OOP, I don't see anything wrong with using static methods for procedural programming to make up for PHP's lack of namespaces.

You are not doing anything wrong.
Some classes are used only to contain utility functions (for example the Arrays class in Java), actually called "static methods".
What you are doing is using this feature in substitution of namespaces. For clarity you should use the latter.

Related

Design patterns for making old php code object oriented

New to php .I'm working on an old code in which I have to add many new features.
The code doesn't use any object oriented features of php5 right now but I'll be using them and will try to refactor important and complex old stuff in free time.
I've couple of questions :
1. Being someone coming from java background,ability to access outside functions from within a class seems so wrong which I have to do in order to reuse old functions. Is this a right thing to do ?... feels so unnatural to me, is there any better way to reuse old functions ?
2. Can someone suggest some good design patterns that can be used with old php code to make it little object oriented and make it elegantly work with new features.
Being someone coming from java background,ability to access outside functions from within a class seems so wrong which I have to do in order to reuse old functions
This has always irked me about Java.
There is nothing wrong whatsoever with free functions. The mantra that "everything must be in an object in OOP" is complete rubbish; only things that logically fit inside object types should be so.
So don't worry about it at all.
Can someone suggest some good design patterns that can be used with old php code to make it little object oriented and make it elegantly work with new features.
No design pattern is going to do your refactoring for you.
Design patterns are not magic bullets; the phrase is horribly over-used, and is merely a way to describe oft-used design conventions. Browse through a list of patterns on Wikipedia if you really want, but instead I'd just write your code in the most logical way and if, afterwards, you notice that it happens to conform to someone's idea of a "design pattern" then... well, good for you I guess!
Here are my thoughts:
Unless you have a lot of testing that can ensure that you don't break everything while you refactor your code to utilize an Object Oriented design, I wouldn't recommend changing the way the existing code works. You can accomplish this by wrapping the old functions into logical groupings through the creation of Facade classes that either pass through the functionality to your existing code, or call several of the functions in your existing code if a more complex operation is needed. Your new code would consist of objects that interact with the legacy Facade as needed, and implement the new functionality using proper OO design.
One thing I think is necessary if you are planning to refactor the old code, is to have proper testing in place. I would take a look at SimpleTest if you don't already have proper testing. As far as design patterns go, it would depend heavily on the goals your existing code is trying to accomplish.
You can simply encapsulate the call of this functions in objects implementing particular interfaces
Refer to 1. This is a general rule; just identify some logic "modules" that are currently implemented through different functions and encapsulate and hide this functions behind objects and interfaces.
You could encapsulate access to the old code using the facade pattern to give you a clean interface between your code and the old code.
I have done this quite succesfully with legacy code that was quite badly written (mine, I'm ashamed to say!), were rewriting was not an option.
I finished with a nice clean interface which could be modified easily and was easy to read. It was well worth the extra effort and allowed me to refactor the old code at my leisure as and when time permits (still working on that).
I an idea more than anything.
If in Java you have ever made a static method such as MyClass::someStaticMethod( parameter ) then it's like using a 'free' function.
That's what static methods are really. They're accessible globally and all it really is is a really long name, but otherwise it's a free method.
You might have put them in a 'class' but really it's java's way of creating global functions in a limited sense. If you think about it this way, php free functions don't seem so bad since their names are shorter.

Object Oriented Naming Conventions

What is the name of having code structured with methods attached to objects?
For example:
" ... ".trim
or
obj.method()
At first many would argue this is Object oriented, but php is Object Oriented(well partially), yet it syntax is completely different trim(" ... ").
TL;DR "Object Oriented" and "Everything is an Object" aren't valid answers unlesss......
People constantly suggest PHP is "Object Oriented" and libraries are "Object Oriented", yet PHP library's code is often structured with tons of static classes.
For example RedBean:
R::dispense($bean)
R::store($bean)
R::trash($bean)
That doesn't follow the obj.method syntax, yet is supposedly Object Oriented. Is PHP's object orientation misleading, or is there a better name for obj.method() coding style.
PHP can do both. You can write object oriented code, and you can write procedural code.
Procedural code is much easier to understand and write, and most PHP programmers don't really understand OOP, so they write, what I call, procedural code disguised as OOP.
This includes things like static methods, and singletons.
Much of the core functions of PHP is C heritage, so don't get surprised if it doesn't follow OOP conventions.
The important thing is that calling methods on objects does follow OOP conventions.
Strings in PHP are not considered to be objects but scalar values. Therefore the syntax "..."->trim() cannot work unless the scalar string literal is converted to object first.
There is an open proposal for auto-boxing (auto-converting of a scalar value to object). This would allow the usual object oriented syntax. Auto-boxing, however does have a little performance penalty. See more here:
https://wiki.php.net/rfc/autoboxing
In the case of RedBeanPHP I use static methods for the facade. This is more user friendly than purist OO code. You don't have to know about all the internals of RedBeanPHP in order to use it (there is also an OO way to use the lib). In my opinion RedBeanPHP is really object oriented; behind the facade it uses inheritance, interfaces, polymorphism and patterns like adapters, factories, observers.
Also, I believe OOP is more like a way of thinking than just a syntax thing. For instance you can just as well craft object oriented systems using structs and function pointers or like GTK does. OOP features in languages are just to facilitate. Also, because PHP is a dynamic language (in contrast to static typed) it does not have to rely on types, it can just scan objects for desired behaviours. In my opinion this is a good thing because it is more flexible and more maintainable the deep class hierarchies like in Java. I used to be an OO purist but I have recently embraced OOP-pragmatism; just use the best of both worlds.

When it is necessary to use Classes in PHP

I am a wordpress plugin developer. I saw the source of many pluginsand many plugin use "classes" in them and some without classes.
Many huge coded plugins like "wp-postratings" does not use Classes and some small plugins use Classes.
edit:
Since classes have private, public and protected access specifiers, i feel a taste of security
Does it increase security?
Other than PHP does other languages require classes ?
Is it compulsory to use Classes ?
I need some suggestions.
No, it's not compulsory, nor does it increase security per-se. it's just a different style of programming.
Most programmers would agree that object-oriented programming (classes) has many advantages over modular programming (functions). But that's more of a religious debate that I'd rather not get into :)
You should read about Object Oriented Programming. It is not compulsory to use classes but it can make code organization and maintenance of your code easier.
It's obviously not a technical requirement, but if the code structure of your plugin can be described in 2 or more classes, I'd say go OO. It doesn't have anything to do with security but it might make your code cleaner and easier to maintain.
As Eric already said, it's not compulsory, nor does it increase security per-se.
One huge advantage, however, is that it simplifies prefixing and reduces the risk of accidentally causing an error from redeclaring a function.
I always use OOP when I can.
Unless you have a good reason not to, I recommend always using classes. There is no real downside to using them.
Using classes is not mandatory it just helps you and other developer who will modify your code to understand it better.
In my opinion you should use classes whenever it's necessary.
You do not have to write code in an Object Oriented Fashion. You can write procedural code in PHP as well. Many projects do, Drupal, if I am not mistaken is one of them.
At the end of the day. Use the programming paradigm that is best suited to the task at hand, whether it be procedural, functional or OOP.

Utilities file in php?

What is the best way to deal with "utility" functions in a OOP PHP framework? Right now, we just have a file with several functions that are needed throughout the system. (For example, a distribute() function which accepts a value and an array, and returns an array with the value distributed in the same proportions and same keys as the input array.)
I have always felt "dirty" using that because it's not object-oriented at all. Is it better practice to move these into various classes as static methods, or is that just a semantic workaround? Or is there just going to be a level in a framework where some stuff is going to fall outside of the OOP structure?
I tend to make a Util() class that contains only static methods, has no attributes, and is not inherited from. Essentially, it acts as a "namespace" to a bunch of utility functions. I will allow this class to grow in size, but will occasionally split of methods into their own classes if it is clear that those methods are designed only to work with certain kinds of data or if it is clear that a group of related methods should be grouped into a class along with, perhaps, some attributes.
I think it's perfectly OK to deviate from purely OOP practices so long as the code that deviates is well-organized and is not creating architectural flaws in your system that make it harder to understand and maintain.
I've always been more pragmatic about questions like these.
If you want to go full-OOP, you should obviously stick these into classes. However, these classes are only going to be container classes, because they don't really represent objects of any kind.
Also: using classes would require you to either have an instance of that class, using the singleton pattern or declaring every function static. The first one is slower (okay, might not be that much, but in a large framework things like that get large, too - especially in interpreted languages like PHP), while the second and third ones are just plain useless and simply an OOP wrapper for a set of functions (especially the third approach).
EDIT: Feel free to prove me wrong. I might be. I'm not too experienced and always saw it that way, but I might be wrong.
I always think of utility functions as extensions of the standard php functions. They are not object oriented because you don't really get any benefit from making them OO.

Has anyone attempted to make PHP's system functions more Object-Oriented?

I'm just curious if any project exists that attempts to group all (or most) of PHP's built-in functions into a more object-oriented class hierarchy. For example, grouping all the string functions into a single String class, etc.
I realize this won't actually solve any problems (unless the modifications took place at the PHP source code level), since all the built-in functions would still be accessible in the global namespace, but it would certainly make usability much easier.
Way too many times. As soon as someone discovers that PHP has OO features they want to wrap everything in classes.
The point to the OO stuff in PHP is so that you can architect your solutions in whichever way you want. But wrapping the existing functions in Objects doesn't yield much payoff.
That being said PHP's core is quite object oriented already. Take a look at SPL.
I think something like this is intergral for PHP to move forward. Being mainly a .Net programmer, I find PHP painful to work in with it's 1 million and 1 global functions. It's nice that PHP 5.3 has namespaces, but it doesn't help things much when their own libraries aren't even object oriented, let alone employ namespaces. I don't mind PHP as a language so much, but their API is terribly disorganized, and it probably needs a complete overhaul. Kind of like what VB went through when it became VB.Net.
To Answer your question, Yes there exists several of libraries that do exactly what you are talking about. As far as which one you want to use is an entirely different question. PHPClasses and pear.org are good places to start looking for such libraries.
Update:
As the others have suggested SPL is a good library and wraps many of built in php functions. However there still are lots of php functions that it does not wrap. Leaving us still without a silver bullet.
In using frameworks such as Cakephp and Zend (others too), I have noticed that they attempt to solve some of these problems by including their own libraries and building basics such as DB connectivity into the frame work. So frameworks may be another solution
I don't agree. Object Oriented Programming is not inherently better than procedural programming. I believe that you should not use OO unless you need polymorphic behavior (inheritance, overriding methods, etc). Using objects as simple containers for code is not worth the overhead. This is particularly true of strings because their used so much (e.g. as array keys). Every application can usually benifit from some polymorphic features but usually at a high level. Would you ever want to extend a String class?
Also, a little history is necessary to understand PHP's odd function naming. PHP is grounded around The Standard C Library and POSIX standard and uses many of the same function names (strstr, getcwd, ldap_open, etc). This is actually a good thing because it minimizes the amount of language binding code, ensures that a full well thought out set of features (just about anything you can do in C you can do in PHP) and these system libraries are highly optimized (e.g. strchr is usually inlined which makes it about 10x faster).

Categories