Why should I start writing object-oriented code in PHP? - php

I have been using regular PHP for some time now. My formal code training is zero. Whatever I've learned I've found here, on the PHP documentation site, the MySQL documentation, etc.
I write PHP from scratch. I use functions for tasks that re-occur, I apply MVC to write more maintainable code, and I recently wrote a nice little library with some of my functions so I can save time in future projects. Long story short, without being some sort of guru, I have a decent relationship with PHP, and so far it seems to get things done for me.
So my questions are the following: Why should I start writing object-oriented code in PHP? How will it make my programming life better and why is it better than the traditional way of doing things?

OOP was made to make programming languages more similar to real life.
What does that mean?
We live in a world of objects. You are an object (Person), you live in an object House, that House object (as well as any other House object) has an House::$address and House::$number, your house probably contains other objects such as LivingRoom and Kitchen. The Kitchen can hold Oven and Stove and Refrigerator, which are all extensions of the KitchenAppliance object.
OOP programming takes that approach, and incorporates it into the programming world.
How does it help me?
Well, there are several things:
It makes your code more maintainable. Instead of dividing your program into tasks (functions), you divide it into objects, if you think of a database connection as an object (meaning, there can be multiple database connections, they share methods and properties, but each is preformed on a different instance), it makes it easier to understand and maintain.
It makes your code more readable. You define an object with the class decleration, and then call it with the new ClassName() keyword.
It allows for extensibility and flexibility. Just like KitchenAppliance can be extended into Oven or Stove, so can your objects and classes.
Summary
OOP programming comes with many advantages. It requires a slightly different way of thinking, but eventually, it's worth it.

You have received a lot of comprehensive answers, so I will use one argument: design patterns. (http://en.wikipedia.org/wiki/Software_design_pattern).
You can find tones of solutions for commons problem, which can save your time and improve quality of your code.
Some design patterns examples:
Strategy pattern (http://en.wikipedia.org/wiki/Strategy_pattern) - for using different alghoritms/solutions in class without changing it
Observer pattern (http://en.wikipedia.org/wiki/Observer_pattern) - you can invoke different actions (and register them during execution) - when state of object changes.
Decorator pattern (http://en.wikipedia.org/wiki/Decorator_pattern) - you can extend your object dynamically, and use new objects in same manner as old.
Franky speaking, if you want to better understand OOP, you have to:
Learn or understand common design pattern.
Start using unit testing, you will find out that lack of dependency injection can be real pain in bad architecture.
learn and understand OOP principles, like SOLID http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29.
Without this you will be using functions encapsulated in classess, like in namespace, not OOP.

For sure you can write your code without OOP and try to implement designs/patterns like MVC without using just a single object.
I don't want to answer why to program in OOP. This you could read in e.g. on this Stack Overflow question.
I think you want to know, when and why you would fail with your coding behavior:
This would be at the moment when you try to work with another person together. The other programmer would never find your code readable. He will take a long time till he understands how your software works.
I think it's hard to separate tasks in your code for teamwork. How are your files separated, and how is the naming convention? You have to solve this by your own and don't reuse every known pattern.
What are you doing with third-party stuff? How do you integrate them? I do not know any usable library without using an OOP schema...
There are many more problems which are surely possible to solve, but every time you lose the possibility for others to understand your code and to reuse it in other programs...

One word: cohesion.
When you start developing software using objects (especially when those objects use Dependency Injection), you find that common functionality starts to gravitate into their own specialised classes that are reused. This makes maintaining and enhancing the software MUCH easier, and results in higher quality software.
Example:
Many applications use sessions, for storing all sorts of stuff. When all session data is managed by a specialised session manager class, all the code that is responsible for dealing with the session is kept in one place. If you want to change the way you application uses session data (perhaps to make it more secure, or more efficient), you only need to change code in one place.
I made the jump to OOP PHP three months ago and it is one of the best things I have done.
I started off with PHP Object-Orientated Solutions and have just finished Real-world Solutions for Developing High-quality PHP Frameworks and Applications. Both of those books have helped me a lot, and I highly recommend them.
The learning curve is quite high. But I guarantee, you will be glad you've turned to OOP.

With OO you can develop applications a lot faster and in a cleaner way. You could easy to reuse your extisting classes with extending them (reducing your code base).
With OO design you only have to deal with small pieces of codes at any one time, not a bunch a functions in a file with 3000+ lines of code. You should also look after the
SOLID guidelines.

Related

Starting a large PHP project. Is OOP necessary or is it just a preference?

I started learning PHP awhile ago. I guess I'm fairly okay in it. I want to write a Content Management System, just as a project for myself, however long it may take. To be more specific, a simple gaming CMS where users can log in, post clan statistics, post in a forum, have user profiles, upcoming matches etc, various other modules you can install or code yourself. It's been done before, but I feel like I would learn a lot by going through with this.
To the experienced coders:
What is required to undertake such a project?
Any framework preference?
Is OOP necessary?
Are there certain ways to go about making such a large-scale project?
I've heard of various frameworks like CakePHP, codeigniter, and Zend, but I'm not sure what I should make of it.
The most important step in any project is PLANNING.
Plan everything you can , database (tables , columns , relations) , process-flow and such on.
Nothing is necessary but OOP is recommended because:
You won't get lost in your own code
Easy to edit and to add (reflexable for changes)
Cakephp , codeigniter are frameworks and they will save you lot of development time.
Instead of writing classes for each type of models you have (posts , members ...)
you run a simple command and it will create a basic app for your needs.
From my personal experience so far i would suggest you (at least) try making the system on your own since the experience and knowledge gained throughout the process of creating complex systems is by far the best hands on practice you will ever get.
Whether to use a specific framework or not is particularly up to you and whether you feel up to the task of achieving the system development on your own, since using a framework would also require learning the specific framework as well.
For OOP i would highly recommend it since it makes everything a lot easier. If you've never worked with object oriented principles before, you might find it a bit challenging at the beginning, but once you get over the learning curve you'd be more than satisfied with the result, with what you've learned and how easy and organized your whole system will look, especially when you have to make small changes or updates.
Since we are talking about a relatively large system as you suggest, i personally cant stress enough, how important planning and analysis is. Try to write down in details all the data you will need, make drafts and plan your database tables as thorough as you can since if during the process you find out that you've forgotten something or something just doesn't feel right, you might have to recreate classes, databases etc. to make it all run smoothly.
OOP is in the end a matter of preference, but there are a few notable advantages. The very first one that comes to mind is security. Parametized queries with mysqli, which are designed to function in an OOP kind of way, transactions, if you will have any.
If you want CMS, then you will also probably have to display quite a lot of data from the database, which will require pagination. Instead of having to re-write a "procedural" pagination algorithm, you could approach everything with OOP with a single class.
Ultimately, it is still a matter of preference but as far as I know, oop comes with many many advantages in real world applications. Good luck with your project!
I'll just reiterate what's already been said here and say this: OOP is a utility, and never a requirement. I'm an OO person myself and I tend to think easier in those terms after having done it for years, but I don't think I've come up across more than a couple of things that I don't think I could have done without OO practices (one of which being a particle effects engine, which is kind of a given).
That being said, there are definitely times where OO is more a hindrance than an boon. What you need to do is sit down and really visualize your project as a whole. When you're looking at the big picture, do you see things as encapsulated objects? Will you have one block of code that you will be using lots of times over to describe things that are similar but slightly different? Or, is your project a bit more linear where you can see most of your scripts running in the traditional "top-down" format?
Well, the point of OOP is to make programming more similar with the real world. In the real world, you're dealing with objects. Your job is an object of class Job, you are an object of class Employee which extends the class Person, you go home to an object of class Apartment which is contained in an object of class Building, which is contained in an object of class Block.
My point is, the point of OOP is to make life easier for you, you can designate a forum post as an Object, as you can for users and whatnot. The whole structure of data you can create in OOP is far more complex, and easy to understand than procedural PHP.
Eventually, it's all in your preference, but yes, if you asked me whether I'd recommend you use OOP on a project of this scale, I would definitely say yes.
As for your other questions:
What is required to undertake such a project? - Planning, and lots of it. Plan ahead anything you might need (in terms of database, existing projects/classes, files, pages). Also plan in for extensibility, to add modules and tables in the future.
Any framework preference? - I'm not a huge fan of frameworks, but I suggest you do learn the concept of MVC and single point-of-entry.
i think framework will help you a lot.. i mean various repetitive task can be easily omitted
and for a large project OOP is highly recommended for simplicity without OOP your code will be very evil and very hard to maintain
You should first look for some good framework - working from beginning is quite difficult. You should first create some kind of block diagram of necessary parts of your application and corresponding database/tables.
OOP is recommended because it could save you a lot of time.
One good framework look here: http://code.google.com/p/phpstartapp/

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

How do i get out of the habit of procedural programming and into object oriented programming?

I'm hoping to get some tips to kinda help me break out of what i consider after all these years a bad habit of procedural programming. Every time i attempt to do a project in OOP i end up eventually reverting to procedural. I guess i'm not completely convinced with OOP (even though i think i've heard everything good about it!).
So i guess any good practical examples of common programming tasks that i often carry out such as user authentication/management, data parsing, CMS/Blogging/eComs are the kinda of things i do often, yet i haven't been able to get my head around how to do them in OOP and away from procedural, especially as the systems i build tend to work and work well.
One thing i can see as a downfall to my development, is that i do reuse my code often, and it often needs more rewrites and improvement, but i sometimes consider this as a natural evolution of my software development.
Yet i want to change! to my fellow programmers, help :) any tips on how i can break out of this nasty habbit?
What is the point in using object-oriented programming when you cannot find good reasons or motivation to do so?
You must be motivated by the need to conceive and manipulate ideas as objects. There are people who feel the need to be perceptive of concepts, flow or functions rather than objects and they are then motivated towards programming oriented towards concepts, ideas, or functional flow.
Some 13 years ago, I switched to c++ from c simply because there were ideas I needed but c would not easily perform. In short, my need motivated my programming oriented towards objects.
The object-oriented mind-set
First, you have bytes, chars, integers and floats.
Then your programme starts being cluttered with all kinds of variables, local and static.
Then you decide to group them into structs because you figured that all the variables which are commonly passed around.
Conglomeration of data
So like printer's info should have all its variables enclosed into the Printer struct:
{id, name, location,
impactType(laser|inkjet|ribbon),
manufacturer, networkAddr},
etc.
So that now, when you call function after function over printer info, you don't have functions with a long list of arguments or a large collection of static variables with huge possibilities of cross-talk.
Incorporation of information
But data conglomeration is not good enough. I still have to depend on a bunch of functions to process the data. Therefore, I had a smart idea or incorporating function pointers into the Printer struct.
{id, name, location,
impactType(laser|inkjet|ribbon),
manufacturer, networkAddr,
*print(struct printer),
*clean(struct printer)
}
Data graduates into information when data contains the processes on how to treat/perceive the data.
Quantization of information
Now laser, ribbon and inkjet printers do not all have the same set of information but they all have a most common set of denominators (LCD) in information:
Info common to any printer: id, name, location, etc
Info found only in ribbon printers: usedCycles, ribbon(fabric|cellophane), colourBands, etc
Info found only in inkjet: ink cartridges, etc
Info found only in lasers: ...
For me and many object-oriented cohorts, we prefer to quantize all the common info into one common information encapsulation, rather than define a separate struct/encapsulation for each printer type.
Then, we prefer to use a framework which would manage all the function referencing for each type of printer because not all printers print or are cleaned the same way.
So your preference/motivation oriented away from objects is telling you that your programming life is easier if you do not use objects? That you prefer to manage all those structural complexities yourself. You must not have written enough software to feel that way.
The necessity of laziness
Some people say - necessity is the mother of creativity. (as well as, Love of money is the root of evil).
But to me and my cohorts - laziness in the face of necessity are the parents of creativity. (as well as the lack of money is the other parent of evil).
Therefore, I urge you to adopt a lazy attitude towards programming so that the principle of the shortest path would kick into your life and you'll find but have no other choice than to graduate towards orienting yourself towards programming with objects.
Step 1. Read a good Design Patterns book. http://www.oodesign.com/
Step 2. Pick something you already know and rework it from an OO perspective. This is the Code Dojo approach. Take a problem that you already understand, and define the object classes.
I did this -- and wrote down what I did.
See http://homepage.mac.com/s_lott/books/oodesign.html#book-oodesign
You can do the same series of exercises to get the hang of OO design and code.
The OO mindset is based on principles that lie at a much more basic level than design patterns. Design patterns are somehow fashionable these days (and have been for a while), and they are useful, but they are just one more layer that you can put upon more basic stuff that you absolutely must learn and master if you want to do OO properly. In other words: you can do OO perfectly without design patterns. In fact, many of us did OO well before the phrase "design patterns" was even coined.
Now, there is stuff you can't do without. I suggest you start at the basics. Read and understand "Object-Oriented Software Construction" 2nd edition by Bertrand Meyer. It's probably the best book on OO programming around, both in width and depth. That is if you're interested in programming.
First, congrats on taking steps to learn something new! I hate it when developers decide to NOT evolve with technology.
As far as moving from procedural programming to OOP, I would say that one thing that you can do is take an existing app (as others have mentioned) and, before you even open a text editor, sit down and think about how each aspect of the application would be converted. I have found that more than half of OO programming is defining the conceptual objects in your mind first.
Again, I will agree with everyone's recommendations on design patterns. Specifically, I would look into the MVC (Model-View-Controller) pattern as this one might be the easiest one to grasp. You have already written code, so you should be able to look at your existing applications and begin putting each part into the M,V or C categories.
Best of luck and have fun!
There are already quite a few answers about where to find information on programming in an object-oriented fashion. Indeed, there are many great books out there that will define the basic concepts however I think the question was more on how to "stick with it" through development for someone new to the method.
Of the many concepts in object-oriented programming, the main one that will keep you on track as a newcomer is encapsulation. Does my class know how to take care of itself? Does my class have behaviour? If it doesn't, then you don't have a class, you have a structure and you'll likely be writing a lot of procedures to change its state (as it's said, "you are back to writing C in Java"). Does my class only expose methods publicly that are required for its use? Those questions may not be terribly elaborated upon but perhaps consider this thought experiment when designing your classes: What if each one of your application's classes were to be developed and maintained by a different developer on the internet and the classes also had to interact with eachother over the internet. Would each developer agree that the class they are writing and maintaining adheres to the single responsibility principle and therefore be happy that they aren't maintaining what should be someone elses code?
Regarding the design of class interfaces, consider writing all of the code that uses your classes first. Don't worry about what has to happen at the metal yet. You should be able to stub out the entire program in terms of the class relationships before you write your first bit-twiddling implementation detail. If you can't do this without twiddling bits or making a variable public, then it is time to go back to your class relationship diagram and see if you are missing an abstraction. Phrased another way, use your code before you write your code. Do this first, and you might be suprised how clean your code and interfaces turn out if you've never done it before.
While design patterns are certainly good to learn, and some are extremely powerful, they aren't generally intrinsically object-oriented and as some argue (and I tend to agree) design patterns are often just exposed weaknesses in the language. One language's design patterns is another's basic founding principles. So when starting, don't get hung up on whether or not some relationship is a good candidate for a bridge or a facade; this is not specific to object-oriented thought, this is related to what a specific language's constructs afford.
Don't.
First, learn writing. Second, learn user experience and interaction design. Third, learn business analysis. Fourth, learn role modeling.
Now that you know what objects are, you will come to see that objects are not found in code. They are found at runtime; in the space between the machine and the user's mind. This is what object orientation really means. Unfortunately recent academia has twisted it into an engineering concept. Nothing could be further off the mark. And try as they might to emulate, the end result is crap. Why? Because the "OOP" paradigm as the industry knows it today is built on a fundamentally flawed idea: decompositional analysis of identity. How is this flawed? Because identity in and of itself is meaningless. It is void. In a mathematical sense, in a philosophical sense. This is not how a human being perceives and interacts with the world.
Canon: Alan Kay, Trygve Reenskaug, James (Jim) Coplien
How I wish I was in your position. :)
I think it helps to first skim over some existing, decent, proven object-oriented code (e.g. Qt source code) so you can get a feel for "how it's done". After that, learning from a book or creating your own framework will be much more effective.
In general, it really helps to see things in context before reading about and practicing them, as it gives you moments to say to yourself, "Oh, that's why they did that!" At least that's how it works for me.
The hard part of OO is which stuff should be put together into one object. As you already mentioned the evolution of your source code, here you have a simple guideline on how to evolve your source code towards an OO design:
"Put stuff together that changes together."
When two pieces of code have similar change velocities, that's a hint that they should be placed in the same object. When the change velocities are different, consider placing them in different objects.
This is also known as "Change Velocity".
If you follow that guideline your code will naturally evolve towards a good OO design. Why?
Fragments of code often have similar
change velocities if they access a
common representation. Every time the
representation changes, all the pieces
of code that use it must change at
once. This is part of the reason we
use objects as modules to encapsulate
representation. Separating interface
from implementation makes sense under
this guideline too - the
implementation changing more often and
thus having a higher change velocity.
If a class has a stable part and an
unstable part, that's a difference in
change velocity that suggests moving
the stable part to a (possibly
abstract) base class.
Similarly, if a class has two parts
which change equally often but at
different times or in different
directions (that is to say, for
different reasons), then that again
suggests refactoring the class.
Sometimes replace "class" with
"method". For example, if one line of
a method is likely to change more
often than the rest - perhaps it is
the line which creates a new object
instance and contains the name of its
class - consider moving it to its own
routine. Then subclasses can easily
effect their change by overriding it.
I came across this concept on C2 wiki many years ago, but I've rarely seen it used since. I find it very useful. It expresses some crucial underlying motivation of object oriented design. Of course, it's therefore blindingly obvious.
These are changes of the program.
There is another sense of change
velocity - you don't want instance
variables changing at different rate,
or rather that is a sign of potential
problems. For example, in a graphics
editor you shouldn't keep the figures
and the handles in the same
collection, because the figures change
once a minute or once an hour and the
handles change once a second or once a
minute.
In a somewhat larger view, you want a
system to be able to change fast
enough to keep up with the changes in
the business.
PS: the other principle that you should follow is "Law of Demeter", that is, an object should only talk to its friends. Friends are: yourself, instance variables, parameters, locals, and members of friendly collections - but not globals and static variables.
You might consider using the CRC (Class/Responsibility/Collaboration) card approach to OO design. This is nothing too scary - just a way to sort out what your objects should be, and which object should be responsible for which tasks by writing stuff down on a bunch of file cards to help clarify your thoughts.
It was originally designed as a teaching tool for OO thought, and might work for you. The original paper is at: http://c2.com/doc/oopsla89/paper.html
A poster above suggested programming in Smalltalk to force you into OO habits, and to an extent that's a good suggestion - Smalltalk certainly did me a lot of good, but
a) you may not have the spare time to learn a new language. If you do, great.
b) I used to tutor a university course in OO programming, using Smalltalk, and the students did an excellent job of proving that old joke about how "You can write FORTRAN in any language".
Finally: when I was learning about OO (from books) I got the impression that you subclassed a lot, creating complicated class hierarchies. When I started working with OO programmers I realised it didn't happen as often as I thought. I think everyone makes this mistake when they're learning.
The only way to write better code is to write more code. Take a project you've implemented procedurally and convert it to OOP (assuming you're working in a language that supports both). You'll probably end up with a fragile, tightly coupled solution the first time around, but that's ok. Take the bad OOP implementation and start refactoring it into something better. Eventually, you'll figure out what works, and what doesn't.
When you're ready to take the next step, pick up a Design Patterns book and learn some of the OOP design terminology. This isn't strictly necessary, but it will give you a better grasp of some of the common problems and solutions.
I think you should convince yourself by researching all of the downsides with procedural programming, for example (some buzzwords following, watch out): scope, state ... practically you'd be able to extract many terms just by reading examples of design patterns (read: common examples of using objects together.)
Stressing yourself into learning something you don't believe in won't get you anywhere. Start being really critical on your earlier work and refactor it to avoid copied code and using the global scope, and you'll find yourself wanting more.
For me the ah-ha moment of OOP was the first time I looked at code and realised I could refactor common stuff into a base class. You clearly know your way around code and re-use, but you need to think around classes not procedures. With user authentication it's clear you're going to have a username and password, now they go into the base class, but what if you need a tokenId as well, re-use your existing login base class, and create a new subclass from that with the new behaviour, all your existing code works without change.
See how that works for you.
Well, first off design patterns are about the worst thing to pattern your programming to.
It's just a big set of things. It's nothing to do with OOP, and most of them such as singleton are constantly used for all the wrong reasons (ie initialization). Some of these things you have to use so telling you about them is pointless, others are counterproductive, and the rest are just special case things. If you try to learn anything this way everything will start to look like some bizarre doodad someone came up with for a very special problem or because they needed infinite genericity (which is seldom true). Don't let people con you into using a million iterators and templates for no reason and make things ten times more complicated.
Really OOP is a simple subject that gets massively overcomplicated. Unfortunately in C++ it has a lot of issues but really simple virtual methods are what matters. Pure virtual base classes used much like a java interface object are the most useful but also just plain virtual methods here and there will come in handy.
It's mostly been overblown. It also doesn't lend itself well to every problem. If you make database and gui stuff it lends itself well to that. If you make system tools it is usually not as helpful.
I found that one of the things which has really helped solidify the benefits of OOP for me has been writing unit tests with a mock object framework (such as EasyMock). Once you start to develop that way, you can see how classes help you isolate modules behind interfaces and also allow for easier testing.
One thing to keep in mind is that when people are first learning OOP, often there is an overemphasis on inheritance. Inheritance has its place, but it's a tool that can easily be overused. Composition or simple interface implementation are often better ways of doing things. Don't go so far in attempting to reuse code via inheritance that you make inheritance trees which make little sense from a polymorphism standpoint. The substitution principle is what makes inheritance/interface implementation powerful, not the fact that you can reuse code by subclassing.
A great step would be to start of with a OOP framework, you can still write procedural code in the framework but over time you can refine your coding habits & start converting functionality into objects.
Also reading about patterns & data modeling will give you more ideas about to code your logic in a OOP style.
I have found that a very intense way learning to train abstraction in programming is to build a OOP library with a defined functionality, and then to implement two projects with similar but still different requirements that are building on that library, at the same time.
This is very time-consuming and you need to have learned the basics of OOP first (S.Lott has some great links in the other answer). Constant refactoring and lots of "Doh!" moments are the rule; but I found this a great way to learn modular programming because everything I did was immediately noticeable in the implementation of one of the projects.
Simply practice. If you've read everything about OOP and you know something about OOP and you know the OOP principals implemented in your language PHP... then just practice, practice and practice some more.
Now, don't go viewing OOP as the hammer and everything else as the nail, but do try to incorporate at least one class in a project. Then see if you can reuse it in another project etc..
Learn a new language, one that helps to move you gently to OOP. Java is nice, but a bit bloated, though. But its system library is mainly OO, so you are force to use objects.
Moving to another language also helps you not to reuse your old code :-)
I think it´s important to learn the theory first. So reading a book would be a good start.
I believe that the mechanics of OOP seem completely arbitrary and make no sense until you read a book on design patterns and understand the "why" of it. I recommend Head First Design Patterns. I thought OOP was ridiculous and completely useless until I picked up this book and saw what it was actually good for.
OO makes a lot more sense when you understand function pointers and how it relates to indirect function calls and late binding. Play around with function pointers in C, C++, or D for a little while and get a feel for what they're for and how they work. The polymorphism/virtual function part of OO is just another layer of abstraction on top of this.
Procedural is the right tool for some jobs. Don't act like it's wrong. IMHO all three major paradigms (procedural, OO, functional) are valuable even at a fine-grained level, within a single module. I tend to prefer:
Procedural is good when my problem is simple (or I've already factored it enough with functional and OO that I now have a subproblem that I consider simple) and I want the most straightforward solution without a lot of abstraction getting in the way.
Object-oriented is good when my problem is more complex and has lots of state that makes sense in the context of the problem domain. In these cases the existence of state is not an implementation detail, but the exact representation is one that I prefer to abstract away.
Functional is good when my problem is complex but has no state that makes sense at the level of the problem domain. From the perspective of the problem domain, the existence of state is an implementation detail.

Simple DB Model

I do not have much experience using frameworks or anything so that leaves me with little experience using Models (MVC). I have no interest whatsoever in using a framework at the moment. I am working on a website and I am trying to model some objects but I'm not sure exactly how I should be designing the class.
For instance, right now I have a class with a few public members which can be accessed directly. I have started prototyping some functions (select, delete, update) but I am not sure
If these functions should be static
If these functions should accept parameters or use the class members instead
If these functions should even exist how they do currently
If the entire concept I'm going for is the right thing to do
I can't seem to find any sort of hints on the interwebs as to how to create a model class.
If you're using a factory class then all verbs are usually instance methods and the factory is instantiated with some sort of DB session.
If the verbs are member's of the entity's class select is usually a static method while update is usually an instance method and delete is usually defined both ways (IE: delete(recordID) and entity.delete())
The entire concept is the right thing to do but you're going to do it wrong. Period. Making a scalable model like this takes a lot more time and effort than people have at their disposal. I know you have no interest in using a framework but you should.
My inference from your question is that this is a low profile project, and you have enough flexibility from your boss/client/teacher that you can build it however you want. That in mind, here is what I would think about when working on this.
If MVC is a new concept to you, then Test-Driven Development is almost certainly and alien one as well. However, I first cracked into a real understanding of OOP while doing it, so I suggest you give it a try. Writing some simple unit tests first against your model classes will take you through the exercise of figuring out how those model classes are going to be used. You'll be working with the external API of each of those objects (or groups of objects if you're not a TDD purist), and that will help guide the design of the internals. Check out PHPUnit for getting started, as the documentation has some great examples as well.
I think the TDD approach will lead you to the following conclusions:
Probably not. Static data/methods are usually only useful when you absolutely need one copy of something. I find in web apps that aside from maybe a resource connection like the DB this is rarely the case.
This depends on what the function does. Keep in mind that using local variables implies side-effects, or changes in the state of the object. If the data you need to operate on should not change the state of the entire object, use a parameter and return a value. It's also easier to test these kinds of methods.
Again, writing tests for these functions that illustrate how you'll use them in the application will lead you to a conclusion one way or another about whether you need them or whether they are designed correctly. Don't be afraid to change them.
Absolutely. How else are you going to become comfortable with MVC if you don't roll your own implementation at least once? In fact, it's probably better to grasp the concepts with real experience before you move to a more professional framework. That way, you'll understand why the concepts and conventions of the framework are the way they are.
Oh, and the lack of clarity that you're finding on what a model class is, is probably due to the fact that it's the part of your application that is most customized. This is your data model and domain logic, so a lot of it is case-specific. The best resource, though, IMHO is Martin Fowler, whose excellent book Patterns of Enterprise Application Architecture goes into a lot of detail on how and why to design a particular set of "model" classes with one pattern or another. Here is the online pattern library--obviously the book is more detailed.
Hope that helps somewhat.
When using PHP, I think designing object oriented model adds extra work with little benefits - even when looking on large frameworks, it's common to just use assoc-arrays that you can get from resultsets (see f.ex. the multiparadigm approach of Zend MVC).
While Object-Relational mapping is much more established among strongly typed languages like Java, there are already tools for PHP as well (f.ex. Doctrine). You may check it out if having OO-oriented model is what you want, but be aware that OR-mapping has severe issues of it's own and might be of little use in PHP (haven't tried it myself in a dynamic language yet).
For most newly started project, picking a good framework is usually a way to go - it can save you time and promote best practices (of course after some learning time that's different for every tool out there). When using some framework, you should always try to find out the framework's / community approach to solving specific problems (like model design & data access) before experimenting on your own.
The "correct" way to abstract away data access using object-oriented concepts is a hot-button topic for a lot of people. Put another way, there are several ways to do it and there is no "one right" way.
Rolling your own works best if you are seriously upgrading an existing application. This is because you have a heap of code that is already database dependant and you have some bounds for the necessary refactoring. It also teaches you about abstracting code because a lot of refactoring involves removing (or reducing) code duplication. Once you've done this to completion, you will have a much better idea of how a data model layer should work. Or at least, should work for the way you program. And you will know what not to do next time you build one. :-)
If you're starting a new codebase and haven't worked with a framework or object layer but know you need to build one, then the best advice I can give is to be willing to build one later, and refactor the code to suit when that does happen. Yes, it will likely mean your application will get 90% rewritten a few times.
Writing an object abstraction layer is difficult and you will end up with dense code that is fairly defensive about things, and doesn't take chances. But once you've got it working, you will also know how to build robust code, because it will probably be debugged fairly thoroughly.
No because, static methods are hard to test
It depends of the parameter, life cycle, etc. Impossible to answer without seeing some code.
?
No
OOP requires at least 10 years of experience to have a better view on what is wrong/right/better/worse.
So, if you are not a OOP expert, instead of losing too much time reinventing the wheel, I would suggest:
Use a well-known framework for the technical part
Create your classes/framework for the business/functional part.
(1) Will help you be ready in no time for the classic technical part (Session, database interaction, etc.). Will avoid you to make errors others already did.
(2) This is your core business, it should be "your DNA".
Also, using a well-known/good technical framework will make you read quality code and help you progress. (Be carefull some frameworks are really of poor quality)
When you will have enough experience, you will be able to skip the technical framework part and build/customize your own... because technical framework are usually evil (They serve too many purposes). :)

Categories