When it is necessary to use Classes in PHP - 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.

Related

Is OOP necessary in PHP sites, can't I just apply its concept to procedural code.... cake and eat it?

I know there are countless questions about the difference between OOP and procedural, when to use either and whether the benefits outweigh the extra overhead, learning the syntax, inheritance confusion, etc. Most of what I've found tends to just discuss differences and benefits and not whether its necessary.
I generally mix OOP and procedural within the same sites scripts depending on what I'm doing. I'm still fairly new to OOP and actually quite like the modular nature of OOP and the benefits it gives, even if there's a minor overhead. Inheritance can get a little confusing at times though!
To me the major benefits only seem to be in better organisation and protection of the code. Of which, the developer or team of developers are the only people to appreciate it. I guess there's a case for deployment speed but wouldn't say there's a lot in it for most sites unless you've inherited someone else's birdsnest :)
Is OOP necessary in most PHP apps though, especially when execution speed is the holy grail for most sites? ok, so the milliseconds overhead won't really notice unless a heavy use site but as a fan of electronic music speed is king!
I get using OOP in complex things like gaming and real-time cloud software, but static websites? even database heavy ones?
Does anyone have real world examples of typical sites that benefit from OOP and why?
Assuming both cases are well structured, would heavy use sites like ebay or monster.co.uk benefit more from OOP or the speed improvement of procedural ()? and why?
At least with procedural you can debug from the top down without having to bounce around the script to check classes and extensions and interfaces.
Can't I just apply OOP modular thinking with clear MVC and well commented code?
For example, I keep re-usable functions in include files and group related functions together. All I have to do is include the file like I would a class file and call up the functions. If the function needs to change, it gets changed in just one place, similar to a class.
And a kind of inheritance already exists in procedural without having to jump through hoops to declare it. You don't have the same level of control but it gets the job done nice and quick.
You could even simulate a class by grouping functions within a parent function and use a selector function to access them. That's taking it a bit far though!
Also, as far as I'm aware when a function is called it stays in memory making subsequent uses quicker. Whereas with OOP you would have to create two objects of the various methods to use the same function for two different variables. Correct me if I'm wrong.
Why create an object and use a method to 'get' a value when I could just reference the value directly with procedural?
well done for getting this far, hadn't realised I'd typed so much. Anyway, before I digress any further I'm going to end it here.
So if you've got any good examples of actual sites or parts of sites that benefit from either OOP or procedural I would really appreciate the clarity.
People managed to write good, clear, well organized code long before OO languages became popular. I see no reason why it can't still be done now.
Generally OO principles make it easier (which is one reason why OO is so popular) but they are by no means a necessity.
There are lots of questions here. I recall writing a long essay addressing some of these points while at university, but I don't want to reproduce something similar here, so instead, let me share a few thoughts:
Is OOP necessary in most PHP apps though, especially when execution speed is the holy grail for most sites? ok, so the miliseconds overhead won't really notice unless a heavy use site but as a fan of electronic music speed is king!
I think that if execution speed is a really big deal for you, php is not the right language for your website. Compared to the large performance cost of using an interpreted language, a little overhead is negligiable compared to the advantages of the OOP programming style for creating large systems. Do not discount the importance of making something easy for programmers to do, as this means faster releases, less bugs, and more maintainable code.
I get using OOP in complex things like gaming and real-time cloud software, but static websites? even database heavy ones?
I agree with you here. A nice thing about websites is that they are naturally modular because they are separated into pages. It hard to write code so bad that future programmers can't maintain it (for a fairly simple, static website).
For example, I keep re-usable functions in include files and group related functions together. All I have to do is include the file like I would a class file and call up the functions. If the function needs to change, it gets changed in just one place, similar to a class.
You can write good procedural code, but its harder than writing good OOP code. Weaker programmers are less likely to write insane spagetti code when given an OOP system to work with.
Why create an object and use a method to 'get' a value when I could just reference the value directly with procedural?
This is your only real implemenation question. The idea with Getters/Setters is so that you can change the internal workings of the class without breaking other code that depends on it.
I get using OOP in complex things like gaming and real-time cloud software, but static websites? even database heavy ones?
Implying that you don't want speed in games but want speed in websites.
PHP is never the bottleneck, if it is, write it in C.
Don't write procedural code because it is "faster". That's silly.
Does anyone have real world examples of typical sites that benefit from OOP and why?
Websites benefit from modular code that is maintainable and well organized.
You don't need OO for this, you can do it with functional or imperative styles. However PHP is known for it's ease to write bad code in a procedural style.
I would personally say that it's more likely your code is modular and maintainable if it was OO.
It's not necessary though.
And a kind of inheritance already exists in procedural without having to jump through hoops to declare it. You don't have the same level of control but it gets the job done nice and quick.
In OO programming it's all about encapsulation which means binding a lump of data to some functions that manipulate it.
You can do this just as well with a set of functions which take a data object as the first argument or classes.
Classes and OO just gives you sugar and utility.
It's a tool to write modular code, if it's helps you use it.
Don't pre maturely optimize OO away because it's "slow". If you care about that kind of micro optimization then start writing C or ASM.
I think a lot of people who promote OO are younger and have only ever written/been taught OO and so have a very negative view of procedural as old fashioned and 'legacy'.
IMO it is easy to write modular procedural PHP that is DRY and can be easily maintained. The trick is to use functions and 'include' to reuse standard php and html respectively. At the end of the day PHP is just reading DBs and generating html - there is no specific need to add the extra complexity of OO if you don't want to.

When to switch from procedural to OOP?

In most discussions of OOP it's said that the advantage is re-usability.. You put in some extra work to define your classes, and it saves you time later in being able to create many instances and extensions of those objects.
A corrolary of this seems to be that you shouldn't switch from procedural to OOP programming until the tradeoff of writing up everything into objects is equivelant to the time you'll save.
In general, when is a good time to switch from procedural to OOP programming? Are there any signs/characteristics you generally look for to know your project needs to make that switch?
I'm assuming this question is from the standpoint/paradigm of being a beginner. Once a programmer has experience writing object-oriented code, you can certainly author a project from the beginning using this architecture. In fact, I'd argue that a top-down approach can save you huge amounts of time on larger projects.
For the bottom-up scenario you outline, though, I'd say you'd have to feel it out. Reference this wikipedia article for more information about the different approaches, generically speaking.
Specific to PHP, I'd say you could use this approach for a migration:
Take as much code as you can (ie:
related functions) and place them
into include files.
Create a container class for that file. You can start with just using all the functions by calling them in a static manner, or even using a static (singleton) class.
Gradually convert to an instance paradigm instead of the global data / static function one that is the badness of procedural programming.
This process is a great way to learn the ins and outs of OO, and in the end you will see the benefits. It will also teach you my initial point: that it takes a lot longer to convert something into OO than it does to start with a semblance of good (high-order) design from the beginning.
If it's not a very very simple application, now is the time. In fact, it's arguable that you should always program OOly, because it will be harder when you want to extend your program in the future.
I think it depends on the context. For graphics applications using an existing OOP framework, the tradeoff is instantaneous -- you'd have to go out of your way to write procedural GUI code in some contexts.
However, if you're doing raw data processing and not interoperating with any OOP framework, maybe you'd find that OOP never makes sense.
It may be very time-consuming to switch to OOP withing a project. I doubt it would be profitable, because it requires a lot of coding, a hell of a lot of testing, and then a LOT of refactoring. The whole concept of OOP is different from PP.
So I would recommend not to switch within the project, but start using OOP for new projects as soon as possible. When you feel comfortable, you can start thinking of an OOP design for your existing project(s) and gradually implement features in OOP. It will be a lot of work, though, and it will probably feel like rewriting the entire project.
I would look elsewhere for signs you need to switch. For all the hype--and I'm a big supporter of OOP--code reuse is often only marginally better with OOP languages.
OOP is simple another tool to help organize your code, like functions in the past. It's a great and useful tool. But the main benefits are making it easier to write and maintain your code.
If it were me and moving to OOP required almost a complete rewrite, I'd hold off until some more material benefits of the switch became apparent. If your code works, I don't know why you'd rewrite it.
It depends on the task, but having done both, here's what I would think about:
do you feel the work requires modularity? the ability to manage similar or dissimilar things from a central place? are there many repeating elements? will quick development or administration changes be important?
do you feel the problem you are attacking is predictable and repetitive? is the task best served by following steps to solve or by applying algorithms?
If more like 1, then go for OOP, otherwise if it's more like 2, then go for a procedure approach.
When in doubt, use what you're comfortable with.
It is rarely a good thing to change the programming style of an ongoing project.
You can always apply OO principles to procedural code if you want more clear-cut responsabilities among your entities.
check for instance this very interesting book on OO coding in ANSI-C

Is it some bizarre heresy to use classes without objects?

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.

Classes. What's the point?

I'm fairly new to OOP in PHP, I've made a couple of basic scripts but nothing impressive. All I've really taken from it is that it would probably be easier just make a collection of functions and include them.
The structure of classes seems to just confuse what was otherwise a simple process. And in collating everything into a class it doesn't really add any functionality.
So I'm clearly missing something. Could someone explain what functionality is added by creating classes
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 ...
While it may at first look simpler to just use a set of functions and include them, classes have their strong points. Classes can store variables and those variables are there "later."
Here's an edited example from php.net
<?php
$item_name = 'Widget 22';
$item_price = 4.90;
$item_qty = 2;
$item_total = ($item_price * $item_qty);
echo "You ordered $item_qty $item_name # \$$item_price for a total of: \$$item_total.";
?>
v.s:
<?php
class Item {
protected $name, $price, $qty, $total;
function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
function calculate($qty) {
$this->total = number_format(($this->price * $qty), 2);
}
public function __toString() {
return "You ordered ($this->qty) '$this->name'" . ($this->qty == 1 ? "" : "s") .
" at \$$this->price, for a total of: \$$this->total.";
}
}
$widget22 = new Item("Widget 22", 4.90);
$widget22->calculate(2);
echo $widget22;
?>
Another huge benefit is that you can make more of them. Say you want to calculate the price of another item and print it. Instead of having to duplicate all the fancy logic, you can just call new Item and be done.
A big advantage to OOP is code reuse. An example: Say you design a generic "Socket" class, which communicates with a server at a very low level. Then, I may come along and decide that I want to write an FTP class, which allows a user to download files while connected to an FTP server. I can "subclass" your Socket class and extend its functionality to support FTP, without rewriting your code.
Now, say John wants to write an HTTP class, to interact with HTTP servers. He, too, can subclass your Socket class to accomplish this, without rewriting the low level socket code.
Notice how in this example there was no duplication of socket code; both me and John shared it. Code duplication is bad because if there is an error in the duplicated code, the exact same bug may occur somewhere else in your code and you may not realize it.
More detailed information about classes can be found on Wikipedia.
Classes are a way to organize programs. Classes can be used to represent entities in the real world, or artifacts in our programming world, reducing the complexity of programs by allowing us to reason about them in terms of a higher granularity.
It is well-known in psychology that experts organize knowledge into "chunks" to allow them to reason more easily and quickly about their domain. Classes allow us to reason more easily and quickly about our programs.
In addition, classes allow us to group together the knowledge about an entity together with the methods/procedures/functions/operations that are naturally associated with that entity. Again, this provides a natural way to organize the information in our programs.
There are other advantages of classes, such as inheritance, but primarily classes are a cognitive way of organizing program structure to reduce the complexity.
Just a coupl months back I was posting similar questions about classes, I have been using PHP for a few years now and I really didn't see a need to use classes, they just complicated a simple process like you said, well I finally decided to jump in on the Class train and I am still learning but I am comfortable using them now and WOW I have a completely opposite way of thinking about them now, I think they are the best feature in PHP now!
I will admit they can be overkill for a small application but a large social network site like mine is far from small, it has hundreds of files and now that I am converting over to classes it is structured much better now and easiar to build, update, manage my code and other users could come in and understand my whole site a lot better now that it uses classes. Another great feature is you can break up all those functions you might have into seperate class files and use autoload() function to auto load the correct file only when the class is needed, this is great on a big project too. Classes make things more plug in play.
All I can say is it's kind of one of those things you need to dive into to see the REAL benefits of it.
I have thought exactly the same thing.
I have read a few books on OO-PHP, my favorite being PHP In Action.
Although when I read the books I thought "Hey, this is very useful and interesting information.", I have yet to use a significant amount of OO-PHP.
Simple needs like getting info from the server and JSON-ing it back really dont need OOP. Im sure it is "Best Practice", but for many people's needs it isn't practical. A few classes, like database connection, and similar data handling can be real time savers, but PHP is sometimes easier and quicker to be used only partially OO.
It would definitely be easy to code in procedural programming (that's what your simple process is called) if your website is small. But as your website grow, you will definitely need to sort things.
For example, you will need classes to act as templates for entities to the database. You might need classes to represent each page, and in a single file you might create multiple pages. Thus these are all advantages of OOP.
In another example you have like 40 over functions. You would want to group them together. Putting them in a class as static methods would definitely help. It'll clean things up so that in future when you come back to the same code, everything looks familiar to you.
I always thought the same thing until I started using classes--realizing that it is so much simpler and better.
You should create those functions that you're mentioning, but gather them all within a class. The functions can then within a class share the same variables, and therefore making it simpler when having to use the same functions multiple times.
The best example I can come up with now is connecting to a database.
Instead of having individual functions that connect, sends a query, fetching the results and closing the connection you could wrap all these functions within a class. This would allow you to communicate to the database multiple times using the same functions, without having to make loads of variables tailored for the specific use on the page.
If you're just writing procedural-style functions then slapping them together into a class you're not going to get many of the benefits of OOP. I think that the Open Closed Principle and the Dependency Inversion Principle describe some of the biggest benefits of OOP, which you wont get unless you intentionally design them into your code.
OOP isn't perfectly suited to everything, though. I think procedural programming is well suited to web development. It involves converting a (fairly) simple request into a bunch of HTML, which is a highly procedural task. If it's simpler to include a few functions, there's no point trying to shove an OOP shaped block into a procedurally shaped hole. However, I imagine that OOP would be the better option if the website was very complex.
All of the above poster have really good points. I would highly recommend the following books:
The OO Thought Process: http://www.amazon.com/Object-Oriented-Thought-Process-3rd/dp/0672330164/ref=sr_1_5?ie=UTF8&s=books&qid=1262547120&sr=8-5
PHP5 Objects, Patterns & Practice: http://www.amazon.com/PHP-Objects-Patterns-Practice-Second/dp/1590599098/ref=sr_1_3?ie=UTF8&s=books&qid=1262546817&sr=8-3
OO Design Heuristics: http://www.amazon.com/Object-Oriented-Design-Heuristics-Arthur-Riel/dp/020163385X/ref=sr_1_1?ie=UTF8&s=books&qid=1262546869&sr=8-1
To manage complexity.
Edit: Maybe I shopuld elaborate a bit more.
Programs are complex entities and many ways have been proposed historically to tame their complexity.
Procedural programming, functions, structured programming, abstract data types and object-oriented programming are just models to help programmers manage the mental effort that is required to understand a program.
Object programming will not solve everything, and certainly for a small script it is overkill, but it works great for big applications or systems.
My original answer tries to summarize the full content of the humongous Code Complete book: do your best to manage complexity and make your programs understandable for you and your successors. It's great if you think that object programming will help you in this task, but it's even better that you question its convenience and try to find better ways.
In PHP, classes can, at the very least, save you a bunch of include statements. The lazy loading of the __autoload() function is very handy. Also, you can be confident that function names in different includes won't conflict.
To go beyond that, you can start to think of creating an API around a class. Functions which are needed only by other functions within the class can be marked private. And eventually, you should be able to ignore the actual code in your classes, and just think of them as API calls.
If I call Do::stuff($a, $b) I get this response.
And that's all you need to know. You can forget how it works "under the hood" inside the class.
And then, of course, there's classes with non-static functions. These can do various interesting things that normal functions can't.

Multi-Paradigm Languages

In a language such as (since I'm working in it now) PHP, which supports procedural and object-oriented paradigms.
Is there a good rule of thumb for determining which paradigm best suits a new project? If not, how can you make the decision?
It all depends on the problem you're trying to solve. Obviously you can solve any problem in either style (procedural or OO), but you usually can figure out in the planning stages before you start writing code which style suits you better.
Some people like to write up use cases and if they see a lot of the same nouns showing up over and over again (e.g., a person withdraws money from the bank), then they go the OO route and use the nouns as their objects. Conversely, if you don't see a lot of nouns and there's really more verbs going on, then procedural or functional may be the way to go.
Steve Yegge has a great but long post as usual that touches on this from a different perspective that you may find helpful as well.
If you're doing something for yourself, or if you're doing just a prototype, or testing an idea... use the free style that script languages gives you.
After that: always think in objects, try to organize your work around the OO paradigm even if you're writing procedural stuff. Then, refactorize, refactorize, refactorize.

Categories