Why use classes in php? - php

I want to know why we use classes in php. I have seen in all of open source they use classes for executing query. It means they use classes for getting results, insert query etc. I think this is used for consistency and speedup, but as my knowledge if we execute query using mysql_query(), rather than creating an object link $db->query will execute fast as compare to second one because in object it will goto the function and then it execute it there and after that it return the result but in case of mysql_query() it will execute the query on the same place. So I think mysql_query() will execute fast. So why we use classes and object to execute query, what are the benefits of using classes?

Encapsulation: A class is a useful packet containing the code and the relevant data together, isolated from everything else. That makes it easier to move it around without searching for exact variables, without collisions with existing code/data.
Of course classes have other uses but in scripting environments like PHP, I think the biggest advantage is that.
EDIT: I was objected with "inheritance is more powerful than encapsulation" argument. I think that does not apply to scripting and web scenarios and I'll try explain why:
First, a web page's lifetime is a request/response pair and ideally less than a second. The state is usually preserved in external entities (session, cookies, db etc). Since the page's lifetime is very short, possible states in a web page code are less than, say, a fat client. It's almost always small bursts of code running and finishing the work continuously. Arguably a web page is comparable to a console application in terms of simplicity and number of design parameters. Although number of input parameters can be gigabytes in a form, the relation between UI elements and input parameters are limited to screen resolution, a user's overall capability to what he/she can fill in at once. Therefore in majority of cases we have small number of input parameters, meaning smaller number of states. Of course in combinatorial and "mutable" world that's not true but in the case of "typical web applications", internal state is also small, hence making my claim plausible.
The input and output in a web application is mostly the same: Input is query parameters or form data and output is an HTML document. Therefore in its short lifetime the input processing and output production code is similarly shaped and designed for a web page. I am aware that I omitted a big chunk of "business logic" in the picture and I'll get to that. However let's make sure that we have no use of nifty features of OOP like "polymorphism" and "inheritance" in these parts of our code. There are very well known, long studied, practical and non-OOP patterns for that. It would be at least dumb to invent new ways of parsing query parameters using "polymorphism", "visitor pattern" etc.
The data access is also performed by existing libraries and luxuries like "inheritance" or "polymorphism" have no use there. You can still use classes but that would simply be encapsulation. You can't inherit/reuse MySQL code for writing T-SQL or PL/SQL code. You need a complete replacement. Oh maybe your SELECT * FROM table could be "inherited", and think of possibilities, wow.
Now what we have left? Yes, the business logic. We already mentioned that business logic is also short bursts of information processing. There is no persistent business state in PHP code itself. We know that almost all business operations must take less than a second due to The Web's requirements. Therefore the states you can go through, again, is much less than a full fledged application. You have atomic, isolated business operations going on for majority of cases in a typical web application.
Now let's go back to design. We know that our page consists of these parts:
Input
Business logic
Data access
Output
We already got input, data, output out of the scope of polymorphism and inheritance. Here is our final picture:
Input processing
Business logic
Data access
Output production
Although business logic could be the biggest part of our app, it's still got to be in our one second window in a web application therefore has to be small, aka short lived.
Yes a supercomputer can do a lot in a second but we're still talking in terms of majority, common scenarios. What's common? CRUD is common. That's why Ruby on Rails and Active Record pattern is such a success and gained such a popularity because it increased productivity on one thing: CRUD.
The complexity of a design is proportional to the number of data elements and operations involved. And since we assume that majority of operations are CRUD, we have a fixed number of operations and small number of input parameters, we have a small problem space.
There can be exceptions but for most of the cases a design for a small problem space can't be complex and good at the same time. It's very unlikely that you can use inheritance in a web page's design unless there are vast amount of data points and too much redundance going on behind. I repeat, for most of the cases, it's crude CRUD.
Second, (yes there was a first at the beginning in case you forgot), web app performance is important (if not critical) -remember "one second"- and in a scripting environment it's twice as important.
Object-oriented paradigm relies on a very important low-level mechanism for being useful and performant at the same time: pointer indirection. The ability of a CPU reading pointers and jumping to the address pointed by it with almost no difference than jumping to the address directly. That way we can have a virtual method table used for lookups for correct function call and that way compiler can call object's "some()" method without knowing it's exact type because it's just whatever is in the pointer there, yet it still performs like a crazy horse.
That dream ends in the scripting world. You don't have a CPU natively executing instructions. You have bytecodes produced by PHP compiler and that is interpreted by PHP interpreter. Unlike a CPU, PHP interpreter has to deal with higher level concepts like abstractions, classes, types regardless it's a bytecode. The simple pointer indirection for a CPU is a complex set of operations for PHP. Parsing the operation, understanding the operation, making some sanity checks maybe, and finally performing it with another set of bytecodes.
Therefore the overhead of inheritance in a scripting world is orders of magnitudes slower than in a native environment.
That is acceptable of course, as long as gains are more than losses. And thinking of that the performance loss can be recovered in other ways like upgrading, clustering, it doesn't seem like a problem. That's certainly true and here is my final statement:
For most of the scenarios in web application development, an equally maintainable, equally reusable and possibly more performant design could be achieved without calling upon inheritance/polymorphism, therefore encapsulation is the most common and the greatest benefit in PHP, not inheritance.

There are many reasons for using classes, or OOP (Object Orientated Programming).
Code reuse
Inheritance
Easier maintainability
Encapsulation
There are many more reasons, you should just look up the advantages/disadvantages of using OOP.

Time taken my
$db->query()
mysql_query()
is almost the same.
We do not use classes to get execute the code faster but to organise them.
As your project gets bigger and bigger, you will have difficulty in managing your code.
If you objects then you can instantiate that object and use them again again, and besides your code has less chances to get messed up with others.
Object Oriented Way of coding is the easiest and best practice for managing your code elegantly and hence produce better results.

When we use mysql_query() you have to connect before to the DB with mysql_connect() and mysql_select_db().
Everytimes you make a mysql_connect() it cost.
So you will make one time mysql_connect() and save the $link. And use this link for every mysql_query("...", $link)
In object it's the same but it's more elegant you juste create an instance of the class (so it create a connection to the DB) and use the object has a link.
If you change the DB password, you will change it one time, just in the class.
If you change MySQL for PostgreSQL, you will rewrite your code one time, just in the class. It will not affect the rest of your app.

As #frbry said, we use classes for abstraction. Abstraction is needed to manage and reduce complexity. When you are able to "abstract" operations and data, you are able to focus on other things and not think about the implementation of the "isolated and abstracted" things, when doing other things.
It also helps to change the system in the future with smaller impacts on other parts of the code, and again reduce the complexity of a system.
There is a very good MIT lecture from 1986 that is generally about LISP programming, however it also very well describes, why you need to abstract things in procedures (or black boxes they call them) - the point they make is that software development is all about reducing complexity.
Here is the link: http://www.youtube.com/watch?v=2Op3QLzMgSY

Related

Usefulness of loading instances in OO PHP?

I was asked to do a project in PHP and to make sure it was object oriented. I've done OO and I've done PHP, but never both.
The main benefit of OO PHP (outside of inheritance/polymorphism) seems to be code organization. That's fine; I'm doing that. But where I get stuck is if I should actually be creating instances for every "object."
To me (and maybe I'm being naive here), a web app is all about making very short, stateless requests to alter or retrieve records in a database. The objects can't persist between requests. So it feels rather pointless to load data from the database, construct an object from that data, make a small update, save the data from the object back to the database, and then throw the object away. The loading/saving code seems to be a lot of work for nothing. [clarification: a waste of development time, not processing time... not too concerned about overhead]
The alternative is to have a bunch of singletons (or classes with static methods) that just provide a nice, organized abstraction layer to the database layer. I guess writing code in this manner just doesn't feel truly OO. Am I missing something or is that style fine?
Yes, you could summarise the benefits of OO as "code organization"; but this is true for all languages (not just PHP). In reality, it's more than that; it's about how you think about your data structures and algorithms, i.e. about how they map to concepts in the problem domain, how they relate to one another (ownership, parent-child, polymorphism, etc.), and how they expose clean, consistent interfaces to one another (encapsulation). If these concepts would benefit your application, and outweigh the extra development time vs. a quick-and-hacky procedural solution, then go for it.
I don't think persistence has anything to do with it.
I think you should question why you've been asked "to make sure it was OO". This seems like a pretty arbitrary request without further justification. Normally, the approach should be to write your application in the style that best suits the requirements, not arbitrary whims...
Singletons are essentially just global variables with some namespace sugar added in. There are a few main benefits to programming with objects and classes that you just don't get from straight procedural programming. One is inheritance, as you mentioned. Another is the namespacing - you can have a code to compress the lot into a single include file (more meaningful in interpreted languages like PHP than in compiled languages).
Objects are essentially a collection of functions with a shared state (though singletons make that a global state. Beware.) As you pointed out the benefit is mostly that that state is transparently shared by the functions without needing to explicitly pass it every single call. If you have various functions per request operating on shared data and wish them to be specialized forms of a general set of functions, OOP is probably a good fit.
Since you have been tasked to "make sure it is object oriented", I'd take some time to consider common groups of functions, generalizations of same, etc.
In the end the setup/teardown time of the objects isn't too bad - and it might even save some development time in the future if you do a good job.
I think OOP is just a programming style and has nothing to do with developing an application. What you need is a pattern that provides a sufficient abstraction layer (for example: MVC).
My recommendation is: Fat-Free.
It's tiny, simple and quickly take you to the minimal viable version of your product. It has everything that you might need (Caching, ORM, CRUD, Captcha...) and is so flexible that you can use any pattern and with your custom directories hierarchy.
Check out the extensive documentation. The only issue is that it requires PHP 5.3. I think it's reasonable considering the options and flexibility it offers. It really changes the way you work; you should definitively give it a shot.
Like most things in life answer is somewhere in a middle.
Todays application use ORMs (for example doctrine for php) for different kind of optimization, better understanding of database approach (which is important for larger dev teams), easier update of the code, abbstraction layer that is well known to people who join the project, caching mechanisms,....
Classes with static methods are just fine if you are doing some smaller project on your own, but when more people are involved in progress you simply need something more robust and standardized.

PHP OO vs Procedure with AJAX

I currently have a AJAX heavy(almost everything) intranet webapp for a business. It is highly modularized(components and modules ala Joomla), with plenty of folders and files. ~ 80-100 different viewing pages (each very unique in it's own sense) on last count and will likely to increase in the near future.
I based around the design around commands and screens, the client request a command and sends the required data and receives the data that is displayed via javascript on the screen.
That said, there are generally two types of files, a display files with html, javascript, and a little php for templating. And also a php backend file with a single switch statement with actions such as, save, update and delete and maybe other function. Several pages/screens may use the same php backend.
Recently, I have been adding an server sided undo function that requires me to reuse some code. So, I took the chance to try out OOP but I notice that some functions are so simple, that creating a class, retrieving all the data then update all the related rows on the database seems like overkill for a simple action as speed is quite critical. Also I noticed there is only one class in an entire file.
So, what if the entire php is a class. So, between creating a class and methods, and using global variables and functions. Which is faster?
Writing object oriented PHP will not affect your performance at all. If you use extensions like Zend Optimizer, it can even work faster.
So, there's really no reason not to use the much cleaner and more easily maintainable object oriented paradigm in PHP.
Writing purely procedural code may even lead to a performance drop since optimizations can be much harder and small details that eat up execution time are more likely to occur in such a messy environment.
The question is misguided. The problem is not one of speed, it's one of code organization. Using only global functions and variables, and lots of them, it'll get harder and harder to avoid naming conflicts and keep everything organized. Classes help you package and abstract things. Execution speed is a secondary concern, and in most cases won't increase noticeably, if at all. Development speed though can increase significantly over time, since you'll have to deal less with conflicts.

Is object-oriented PHP slow?

I used to use procedural-style PHP. Later, I used to create some classes. Later, I learned Zend Framework and started to program in OOP style. Now my programs are based on my own framework (with elements of cms, but without any design in framework), which is built on the top of the Zend Framework.
Now it consists of lots classes. But the more I program, more I'm afraid. I'm afraid that my program will be slow because of them I'm afraid to add every another one class which can help me to develop but can slow the application.
All I know is that including lots of files slows application (using eAccelerator + gathering all the code in one file can speed up application 20 times!), but I have no idea if creating new classes and objects slows PHP by itself.
Does anyone have any information about it?
This bugs me. See...procedural code is not always spaghetti code, yet the OOP fanboys always presume that it is. I've written several procedural based web apps as well as an IRC services daemon in PHP. Amazingly, it seems to outperform most of the other ones that are out there and editing it is super easy. One of my friends who generally does OOP took a look at it and said "no code has the right to be this clean"
Conversely, I wrote my own PHP framework (out of boredom) and it was done in a purely OOP manner.
A good programmer can write great procedural code without the overhead classes bring. A bad programmer who uses OOP will always write crappy OOP code that slows things down.
There is no one right answer to which is better for PHP, but rather which is better for the exact scenario.
Here's good article discussing the issue. I also have seen some anecdotal bench-marks that will put OOP PHP overhead at 10-15%
Personally I think OOP is better choice since at the end it may perform better just because it probably was better designed and thought through. Procedural code tends to be messy and hard to maintain. So at the end - it has to be how critical is performance difference for your app vs. ability to maintain, extend and simply comprehend
The most important thing to remember is, design first, optimize later. A better design, which is more maintainable, is better than spaghetti code. Otherwise, you might as well write your web app in assembler. After you're done, you can profile (instead of guess), and optimize what seems slowest.
Yes, every include makes your program slower, but there is more to it than that.
If you decompose your program, over many files, there is a point where you're including/parsing/executing the least amount of code, vs the overhead of including all those files.
Furthermore, having lots of files with little code ain't so bad, because, as you said, using things like eAccelerator, or APC, is a trivial way to get a crap ton of performance back. At the same time you get, if you believe in them, all the wonderful benefits of having and Object Oriented code base.
Also, slow on a per request basis != not scalable.
Updated
As requested, PHP is still faster at straight up array manipulation than it is classes. I vaguely remember the doctrine ORM project, and someone comparing hydration of arrays versus objects, and the arrays came out faster. It's not an order of magnitude, it is noticable, however -- this is in french, but the code and results are completely understandable.. Just a note, that doctrine uses magic methods __get, and __set a lot, and these are also slower than an explicit variable access, part of doctrine's object hydration slowness could be attributed to that, so I would treat it as a worst case scenario. Lastly, even if you're using arrays, if you have to do a lot of moving around in memory, or tonnes of tests, such as isset, or functions like 'in_array' (it's order N), you'll screw the performance benefits. Also remember that objects are just arrays underneath, the interpreter just treats them as a special. I would, personally, favour better code than a small performance increase, you'll get more benefit from having smarter algorithms.
If your project contains many files and due to the nature of PHP's file access checking and restrictions, I'd recommend to turn on realpath_cache, bump up the configuration settings to reasonable numbers, and turn off open_basedir and safe_mode. Ensure to use PHP-FPM or SuExec to run the php process under a user id which is restricted to the document root to get back the security one usually gains from open_basedir and/or safe_mode.
Here are a few pointers why this is a performance gain:
https://bugs.php.net/bug.php?id=46965
http://nirlevy.blogspot.de/2009/01/slow-lstat-slow-php-slow-drupal.html
Also consider my comment on the answer from #Ólafur:
I found especially auto-loading to be the biggest slow down. PHP is extremely slow for directory lookup and file open access, the more PHP function you use during a custom auto-loader, the bigger the slow-down. You can help it a bit with turning off safe-mode (deprecated anyways) or even open-basedir (but I would not do that), but the biggest improvement comes from not using auto-loading and simply use "require_once" with complete fs pathes to require all dependencies per php file you use.
Using large frameworks for web apps that actually do not require so large number of classes for everything is probably the worst problem that many are not aware of. Strip it down at least not to include every bit of code, keep just what you need and throw the rest.
If you're using include_once() then you are causing an unnecessary slowdown, regardless of OOP design or not.
OOP will add an overhead to your code but I will bet that you will never notice it.
You may reconsider to rethink your classes structure and how do you implement them. If you said that OOP is slower you may have to redesign your classes and how do you implement them. A class is just a template of an object, any bad designed method affects all the objects of that class.
Use inheritance and polimorfism the most you can, this will effectively reduce the amount of behaviors and independent methods your classes need, but first off all you need to create a good inheritance map, abstracting your first or mother classes as much as you can.
It is not a problem about how many classes do you have, the problem is how many methods, properties or fields they have and how well are those methods structured. Inheritance reduces the amount of methods to design drammatically and the amount of code to be compiled too.
As several other people have pointed out, there is a mild overhead to OO PHP, but you can offset it by focusing your optimization effort on the core classes that your various other classes derive from. This is why C++ is becoming increasingly popular in the world of high-performance computing, traditionally the realm of C and Fortran.
Personally, I've never seen a PHP server that was CPU-constrained. Check your RAM use (you can optimize the core classes for this as well) and make sure you're not making unnecessary database calls, which are orders of magnitude more expensive than any extra CPU work you're doing.
If you design a huge OOP object hog, that does everything rather than doing functional decomposition to various classes, you will obviously fill up the memory with useless ballast code. Also, with a slow framework you will not make a simply hello World any fast. I noticed it is a kind trend (bad habit) that for one single facebook icon, people include a hole awesome font library and then next there is a search icon with fontello included. Each time they accomplish something unusual, they connect an entire framework. If you want to create a fast loading oop app use one framework only like zephir-phalcon or whatever you fancy and stick to it.
There are ways to limit the penalty from the include_once entries, and that's by having functions declared in the 'include_once' file that themselves have their code content in an 'include' statement. This will load your library of code, but only those functions actually being used will load code as it is needed. You take a second file system hit for the included code, but memory usages drop to practically nothing for the library itself, and only the code used by your program gets loaded. The hit from the second file system access can be mitigated by caching. When dealing with a large project of procedural based PHP, this provides low memory usage and fast processing. DO NOT do this with classes. This would be for a production instance, a development server will show all the penalty of hits since you don't want caching turned on.

Having a single entry point to a website. Bad? Good? Non-issue?

This question stems from watching Rasmus Lerdorf's talk from Drupalcon. This question and his talk have nothing specifically to do with Drupal, by the way... it was just given at their con. My own question also has nothing specific to do with PHP. It is the single entry point in general that I am curious about.
These days it seems that most frameworks offer a single entry point for whatever you build with them. In his talk Rasmus mentions that he thinks this is bad. It seems to me that he would be correct in this thinking. If everyone hitting the site is coming in through the same entry point wouldn't things bog down after traffic reached a certain point? Wouldn't it be more efficient to allow people direct access to specific points in a site without having their request go through the same point? But perhaps the actual impact is not very bad? Maybe modern architecture can handle it? Maybe you have to be truly gigantic in scale before it becomes even worth considering? I'm curious as to what people on this site think about this issue.
In short, Rasmus or the interpretation is wrong.
This shows a clear lack of understanding how computers work. The more something gets used, the more likely it's closer to the CPU, and therefore faster. Mind you, a single point of entry != single point of failure. But that's all beside the point, when people say single point of entry, we're talking about the app, it is a single point of entry for your logic.
Not to mention it's architecturally brain-dead not to have a central point of entry, or reduce the number of entries points in general. As soon as you want to do one thing across your app at every entry point, guess how many places need to change? Having dealt with an app that each page stood on it's own, it sucked having to change, and I assure you, we needed it.
The important thing is that you use a web framework that supports scalability through methods like load-balancing and declarative code.
No, a single-entry point does not in itself make a bottleneck. The front page of Google gets a lot of hits, but they have lots of servers.
So the answer is: It doesn't matter.
Like anything in software development, it depends. Rasmus's objection to the front-controller style frameworks is the performance hit you take from having to load so much code up-front on each request. This is 100% true. Even if you're using a smart-resource loading module/object/etc of some kind, using a framework is a performance trade-off. You take the performance hit, but in return you get back
Encouraged seperation of "business logic" (whatever that is) and Template/Layout Logic
Instant and (more importantly) unified access to the objects you'll use for database queries, service called, your data model, etc.
To a guy like Rasmus, this isn't worth the performance hit. He's a C/C++ programmer. For him, if you want to separate out business logic in a highly performant way, you write a C/C++ Extension to PHP.
So if you have an environment and team where you can easily write C/C++ extensions to PHP and your time-to-market vs. performance ratio is acceptable, then yes, throw away your front-controller framework.
If that's not your environment, consider the productivity increases a front-controller framework can bring to your (likely) simple CRUD Application.
I think one of the biggest advantages you have over having only a single point of entry is security. All of the input going in is less likely to corrupt the system if it is checked and validated in a single place.
I think it's a big misunderstanding discussing this from the point of "one file" vs. "several files".
One tends to think that because the entry point is in a single file, then all we have to focus on is the code in that one file - that's wrong.
All of the popular frameworks has tons of files with entry manipulation code, interpretation code, and validation code for requests. The code is not located in one place, rather is spread around in a jungle of require/include statement calling different classes depending on whats being requested and how.
In both cases the request is really handled by different files.
Why then should I have a single entry point with some kind of _detect_uri() function that needs to call several other functions like strpos(), substr(), strncmp() to clean up, validate, and split up the request string when I can just use several entry points eliminating that code all together?
Take a look at CodeIgniters _detect_uri() function in URI.php. Not to pick on CodeIgniter, it's just an example. The other frameworks does it likewise.
You can achieve the goals of a MVC pattern with a single entry point as well as with several entry points.
This is what I thought at first, but it doesn't seem to be an impact. After all, your entry point is (usually) only doing a couple of things: setting some environment constants, including the bootstrap loader, optionally catching any exceptions thrown and dispatching the front controller. I think the reason that this is not inefficient is because this file does not change depending on the controller, action or even user.
I do feel this is odd however. I'm building a small MVC framework myself at the moment but it's slightly reverse to most frameworks I've used. I put controller logic in the accessed file. For example, index.php would contain the IndexController and it's actions. This approach is working well for me at least.
As most of the php mvc frameworks use some sort of url rewriting, or at least parse anything after index.php at their own, a single entry point is needed.
Besides that, i like to provide entry points per context, say web(/soap)/console/...
Just to add, the thing people usually think is that, since there is one php page, it is a single page serving all requests. Sort of like queuing.
The important thing to note is that, each request creates an instance of the script and thus, the load is the same as if two different pages were being accessed at the same time. So, still the same load. Virtually.
However, some frameworks might have a hell whole lot of stuff you don't need going on in the entry script. Sort of like a catchall to satisfy all possible scenarios, and that might cause load.
Personally, I prefer multi pages, the same way I mix oop and procedural. I like php the old school way.
There are definitely disadvantages to using a front-controller file architecture. As Saem explains, accessing the same file is generally advantageous to performance, but as Alan Storm and Rasmus Lerdorf explain, trying to make code handle numerous situations (such as a front-controller tries to handle the request to every "page" on the site) leads to a bloated and complicated collection of code. Using a bloated and complicated collection of code for every page load can be considered bad practice.
Saem is arguing that a front-controller can save you from having to edit code in multiple locations, but I think that in some cases, that is better solved by separating out redundancies.
Having a directory structure that is actually used by the web server can make things simpler for the web server and more obvious for the developers. It is simpler for a web server to serve files by translating the url into the location as they would traditionally represent than to rewrite them into a new URL. A non-front-controller file architecture can be more obvious to the developer because instead of starting with a controller that is bloated to handle everything, they start with a file/controller that is more specific to what they need to develop.

What are the benefits of OO programming? Will it help me write better code? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm a PHPer, and am not writing object-oriented code.
What are the advantages of OO over procedural code, and where can I learn how to apply these ideas to PHP?
It doesn't help you automatically. You can write worse "OO" programs than structural programs, and vice versa. OOP is a tool which allows you to create more powerful abstractions.
As with every powerful tool, you have to use it properly.
As with every powerful tool, it takes time to learn how to use it properly.
As with every powerful tool you will make mistakes.
As with every powerful tool you will have to practice a lot.
As with every powerful tool you should read a lot about it, and read what other people think. Learn from others.
But, as with every powerful tool, there are people out there who misuse it. Learn to not learn bad practices from them. This is hard.
Objects help keep your code isolated between different sections, so that if you need to make a change to one section you can be confident it won't affect other sections: loose coupling.
Then, when you've done that for a while, you'll start finding that objects you created for one app are also useful in others, and you start getting better code re-use as well. So the new app has part of the work already done, and is using time-tested code: software is built faster with fewer bugs.
People will tell you various things about OOP, from various perspectives. But if you want to form your own opinion, rather than take someone else's, then I suggest reading Bertrand Meyer's "Object-Oriented Software Construction".
Essentially, he takes non-OOP programming techniques, and analyses their basic flaws. He then derives an alternative technique which addresses those flaws. Put another way, he derives OOP from first principles. It's a marvellous piece of work, and very convinving.
Read it, you'll learn the why, when and what in a way that you can back up with reasoning.
Objects help encapsulate complexity. For most PHP programming, it's impossible to write good, clean code for any reasonably complicated application. Writing OO PHP helps you put that code into its own box, isolating it from everything else. This has several benefits.
As long as your object has clearly defined inputs and outputs, the way that the object does what it does doesn't matter at all - storing/retrieving data could go from flat file to XML to memcache to MySQL to Oracle, and you only ever have to concern yourself with one single object.
As long as your object has clearly defined inputs and outputs, you can completely replace it with another object that has the same inputs/outputs. Decide at runtime whether you want MySQL, Postgres, memcached, or HTTP POST/GET requests to a sketchy server in Indonesia.
OO makes unit testing easier. If you can define what a specific object should do (i.e what results it should give you for a given input) then you can easily write code to test thousands of values against that code and check the results, and you'll know instantly if something breaks.
The more of your code you 'hide' in objects, the less of it you have to see when you're using that functionality. I wrote a polling application once in PHP that handled all aspects of polling - database interaction, poll generation, voting, ranking, sorting, and displaying - and I only needed one line of code on my website (Poll::Display()) to implement the entirety of what the app could do - which made maintaining my homepage far easier.
Keep one thing in mind - OO in PHP (even PHP5) isn't very good OO compared to a language like Python or Ruby. The everything-is-an-object model in Python is what made me OO programming really click for me - and as a former PHP programmer (and doubly-certified Zend engineer), I strongly recommend exploring Python's OO if you want to understand what OO is all about. It will help you write better PHP code, at the very least.
Yes, if you really get it.
It helps you visualize how parts of a larger system can interact with each other. It's very useful at the design level.
If you are just writing a few lines of code, the only benefit you will get is that it is generally a little easier to use a library broken into well-designed objects than just functions.
To make good use of it, you also need to follow sound OO design practices. Always encapsulating ALL your data, using many small classes, never large "catch-all" classes. Having the class do your work for you instead of asking it for data and doing the work outside the class, etc.
It's probably not going to help you much for a while, and possibly never if you are always doing small websites (I can't say this for sure, I don't really do php), but over time and on large projects it can be invaluable.
One thing no one has mentioned is that OO code facilitates writing readable code:
sherry.changePhoneNumber();
phoneCompany.assignNewPhoneNumberTo(sherry);
sherry.receive(new PhoneNumber().withAreaCode("555").withNumber("194-2677"));
I get a strange satisfaction from such aesthetics.
The huge win for me is inheritance, or making an object that behaves almost exactly like another but with a few differences. Here's a real-world example from my office:
We needed code to process TIFF files that a customer sent to us, convert them to a standard format, insert some information about the file into a database, then send a result email. I wrote this in a set of classes (in Python, but the idea is the same). The "fetcher" class got emails from a POP3 mailbox and handed them to a "container" class which knew how to read attachments from an email. That class handed each image off to a "file object" class that did the necessary processing.
Well, one day we got a customer who wanted to send PDF files. I subclassed the "TIFF file object" class and rewrote the "normalize" function to take a PDF as input instead, but left every other bit of code untouched. It worked the first time and I was pretty pleased.
A change to our mailserver meant that I needed to fetch emails via IMAP. Again, I subclassed the "POP3 fetcher" so that it could speak IMAP. Problem solved.
Another customer wanted to mail us CDs, so I subclassed the "email container" class with a "filesystem directory" class. Voila - done.
In each of those cases, the new code was 95% similar to the old code. For example, the "TIFF file object" class has about 15 methods. The "PDF file object" class defines exactly one: the method that converts files in a specific format into our standard. All others it gets from its parent class.
Now, you can definitely do the same kind of stuff procedurally, such as by writing:
if fileobjecttype == 'TIFF':
data = <snip 30 lines of code to read and convert a TIFF file>
elif fileobjecttype == 'PDF':
data = <another 45 lines to read a PDF>
elif fileobjecttype == 'PNG':
data = <yep, another one>
The biggest difference is that I believe you can make OOP look much cleaner and more organized. My PDF class looks like:
class PDFReader(GenericImageReader):
def normalize(self):
data = <45 lines to read a PDF>
and that's it. You can tell at a glance that it only does one thing differently than the class it inherits from. It also forces you - or at least strongly encourages you - to make clean interfaces between the layers of your application. In my example, the PDFReader has no idea and doesn't care whether its image came from a POP3 mailbox or a CD-ROM. The POP3 fetcher knows absolutely nothing about attachments, since its job is merely getting emails and passing them along. In practice, this has allowed us to do some pretty amazing things with the absolute minimum amount of coding or redesign.
OOP isn't magic, but it's a pretty fantastic way to keep your code organized. Even if you don't use it everywhere, it's still a skill that you really should develop.
There was a time, back when i first started programming, that i wrote user-oriented code. It worked great, but was hard to maintain.
Then, i learned OO, and the code i wrote become easier to maintain, easier to share between projects, and life was good... for everyone except my users.
Now, i know the true silver bullet of computer programming. I write OO code, but first i objectify my users. Treating people as objects may seem rude at first, but it makes everything much more elegant - you get to write all of your software to work with clearly-defined interfaces, and when a user sends an unexpected message you can merely ignore it, or, if marked with a flag signifying sufficient importance, throw an exception at them.
Life, with OO, is good...
I would argue that OOP suits those who think in 'objects', where an object consists of data as well as the functions that operate on that data.
If you tend to think of functions and the data they operate on as separate things, then you are a procedural programmer.
If you tend to think of functions and the data they operate on as being connected, then you are an object-oriented programmer.
I'd caution against going out and learning about patterns. In order to do object-oriented programming well, you need to teach yourself to think like an object-oriented programmer. You'll need to get to the point where you understand and can name the benefits of:
Encapsulation
Classes vs instances/objects
Inheritance and polymorphism
It will help you to be a better programmer only in the sense that the more styles of programming a programmer knows, the more range in his repertoire for solving problems and writing elegant code. You cannot go off and write all your code object-oriented and automatically have good code, but if you really understand how OOP works, and you're not just copy-pasting some popular design patterns of the day, then you can write some pretty good code, especially when writing a large application.
It seems everybody is responding to your question literally, i.e., the specific benefits/drawbacks of OO.
You should learn OO, but not because OO has any specific magic that you need.
The more general form is:
Q: "Should I learn (OO, FP, concurrent, logic-based, event-driven, ...) programming?"
A: "Yes, learning a new paradigm is always useful, even if you don't use it directly every day."
I would put it this way: If you write anything complex, you should encode the concepts you think in, rather than trying to think in concepts that are somehow native to the language you are using. This way you make less bugs. The formalization of those concepts is called design.
Functional programming lets you define concepts that are associated with verbs, since each function is essentially a verb (e.g., print()). OO programming, on the other hand, lets you also define concepts associated with nouns.
To elaborate on Joeri's answer a little:
The International Organisation for Standardization defines encapsulation as, 'The property that the information contained in an object is accessible only through interactions at the interfaces supported by the object.'
Thus, as some information is accessible via these interfaces, some information must be hidden and inaccessible within the object. The property such information exhibits is called information hiding, which Parnas defined by arguing that modules should be designed to hide both difficult decisions and decisions that are likely to change.
Note that word: change. Information hiding concerns potential events, such as the changing of difficult design decisions in the future.
Consider a class with two methods: method a() which is information hidden within the class, and method b() which is public and thus accessible directly by other classes.
There is a certain probability that a future change to method a() will require changes in methods in other classes. There is also a certain probability that a future change to method b() will require changes in methods in other classes. The probability that such ripple changes will occur for method a(), however, will usually be lower than that for method b() simply because method b() may be depended upon by more classes.
This reduced probability of ripple impacts is a key benefit of encapsulation.
Consider the maximum potential number of source code dependencies (MPE - the acronym is from graph theory) in any program. Extrapolating from the definitions above, we can say that, given two programs delivering identical functionality to users, the program with the lowest MPE is better encapsulated, and that statistically the more well-encapsulated program will be cheaper to maintain and develop, because the cost of the maximum potential change to it will be lower than the maximum potential change to the less well-encapsulated system.
Consider, furthermore, a language with just methods and no classes and hence no means of information hiding methods from one another. Let's say our program has 1000 methods. What is the MPE of this program?
Encapsulation theory tells us that, given a system of n public nodes, the MPE of this system is n(n-1). Thus the MPE of our 1000 public methods is 999,000.
Now let's break that system into two classes, each having 500 methods. As we now have classes, we can choose to have some methods public and some methods private. This will be the case unless every method is actually dependent on every other method (which is unlikely). Let's say that 50 methods in each class is public. What would the MPE of the system be?
Encapsulation theory tells us it's: n((n/r) -1 + (r-1)p) where r is the number of classes, and p is the number of public methods per class. This would give our two-class system an MPE of 499,000. Thus the maximum potential cost of a change in this two-class system is already substantially lower than that of the unencapsulated system.
Let's say you break your system into 3 classes, each having 333 classes (well, one will have 334), and again each with 50 public methods. What's the MPE? Using the above equation again, the MPE would be approximately 482,000.
If the system is broken into 4 classes of 250 methods each, the MPE will would be 449,000.
If may seem that increasing the number of classes in our system will always decrease its MPE, but this is not so. Encapsulation theory shows that the number of classes into which the system should be decomposed to minimise MPE is: r = sqrt(n/p), which for our system is actually 4. A system with 6 classes, for example, would have an MPE of 465,666.
The Principle of Burden takes two forms.
The strong form states that the burden of transforming a collection of entities is a function of the number of entities transformed. The weak form states that the maximum potential burden of transforming a collection of entities is a function of the maximum potential number of entities transformed.
In slightly more detail, the burden of creating or modifying any software system is a function of the number of program units created or modified.
Program units that depend on a particular, modified program unit have a higher probability of being impacted than program units that do not depend on the modified program unit.
The maximum potential burden an modified program unit can impose is the impacting of all program units that depend on it.
Reducing the dependencies on an modified program unit therefore reduces the probability that its update will impact other program units and so reduces the maximum potential burden that that program unit can impose.
Reducing the maximum potential number of dependencies between all program units in a system therefore reduces the probability that an impact to a particular program unit will cause updates to other program units, and thus reduces the maximum potential burden of all updates.
Thus, encapsulation is a foundation stone of object orientation and encapsulation helps us to reduce the maximum potential number of dependencies between all program units and to mitigate the weak form of the Principle of Burden.
I'm a long-time procedural PHP programmer who occasionally dabbles in object oriented PHP. Joel's answer above is an excellent summary of the benefits. In my opinion, a subtle secondary benefit, is that it forces you to better define your requirements from the start. You have to understand the relationships between the objects and the methods that will be acting upon them.
A good book to help with the transition is Peter Lavin's "Object-Oriented PHP".
A large system, such as Wordpress, Drupal, or XOOPS, uses OOP concepts. You can see the benefits of their use there. Code reuse, modularity, maintainability, and extensibility.
You have the ability to modify parts of objects and it affects the entire application; no searching to replace every spot you did some operation (and possibly missing it).
You can reuse objects all over, saving an awful lot of copying and pasting. Patching a bug requires patching the one object, not 16 pages of code that all do the same thing.
When you encapsulate the logic and "hide" the implementation, it's easier to use the objects, both for you 6 months from now when you've forgotten why you did something, and for the nest guy or gal who uses your code. For example, all you do to loop through posts in Wordpress is call a function. I don't need to know how it works, I only need to know how to call it.
OOP is really procedural code wrapped in object methods/functions. You do still need to know how to write decent linear code in order to implement methods and functions of objects. It just makes it far easier to reuse, scale, fix, debug, and maintain your things.
http://www.onlamp.com/pub/a/php/2005/07/28/oo_php.html
I would say there are two primary benefits:
Encapsulation: code in libraries that shouldn't be called from outside the library can be hidden, preventing misuse, and easing changes to the internal structure of the library while preserving the external interface. In a good OO design, changes are introduced more easily once the code is complete.
Abstraction: instead of dealing with arrays of arrays you're dealing with employees, departments, and so on. This means you can focus on the business logic, and write fewer lines of code. Fewer lines means fewer bugs.
Reuse I wouldn't strictly qualify as an OO benefit, because in a purely procedural model smart library organization lets you reuse code as well.
On the other hand, using lots of objects in PHP tends to decrease performance compared to a procedural model, because there is too much object construction overhead for every request. Finding a good balance between procedural-style and oo-style code is imperative.
To learn OO in PHP I'd recommend try to use some good written OO PHP framework.
You may want to look at Zend Framework.
I am a PHP aswell, although I do have a strong OOP background, I would say the best book on using OOP with PHP has to be PHP 5 Objects Patterns and Practice
One of the best thing that I did with OOP in PHP is the class generator.
In any given table, it will involve almost the same SQL operations:
insert
update
select
delete
exists (check if a row exists)
search
list
Now I don't have to write all these SQL statements anymore, except on special conditions. Not only I've cut down coding to 1 minute in doing above, I've also saved time from debugging codes.
So whenever there are changes to the table structure, I simply regenerate the class.
Probably you should try the same as it works for me and my customers like it!

Categories