homepage Welcome to WebmasterWorld Guest from 54.237.213.31
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
When to objectify? That is the question.
Learning OOP, do headers/footer belong as Objects?
Clark

WebmasterWorld Senior Member 10+ Year Member



 
Msg#: 3760081 posted 11:02 pm on Oct 6, 2008 (gmt 0)

I've decided it's overdue to go from procedural programming in php to becoming an OOP(rogrammer). I've resisted it a long time. Used to think this whole concept was crazy. Never learned Java. But when my beloved php went OOP, there's no denying this thing anymore.

And boy is it painful when you're used to doing things proceduraly.

Onto my newbie question. When to objectify.

For a site I'm redoing, I'm including headers and nav and footers. Beginning to wonder if this doesn't "belong" in a class. Where I pass the info (i.e. header/footer/nav) and variables ($title, $breadcrumb etc) to the class as I'm instantiating it.

But not being too clear on OOP, I'm not sure if this is a good use of objects and classes. How can it be an object if it's just basically templating.

Naturally, the same header and nav and footer goes on all the pages, so all that's usually needed is passing the title and nav data to the class.

Help!

 

eeek

WebmasterWorld Senior Member 10+ Year Member



 
Msg#: 3760081 posted 3:52 am on Oct 7, 2008 (gmt 0)

Onto my newbie question. When to objectify.

Only when you want to make the code very hard to read. ;)

sastro

5+ Year Member



 
Msg#: 3760081 posted 5:47 am on Oct 7, 2008 (gmt 0)

Use OOP when you build enterprice scale website

nick279

5+ Year Member



 
Msg#: 3760081 posted 7:13 am on Oct 7, 2008 (gmt 0)

Clark,

If you have a look at the MVC design, may give you some ideas on how to proceed.

I personally hardcode the header/footer/top level menu into a series of templates, and load submenus/data in separately.

Simply doing something like this:-

PHP File (at the bottom)


$page['domain'] = $domain;
$page['breadcrumb'] = $breadcrumb;
$page['header'] = $header;
$page['footer'] = $footer;
foreach(array_keys($page) as $key)
$output = preg_replace("/%$key%/",$page[$key],$output);
echo $output;

Template File

<div id="main">
<br>
%content%
<div id="breadcrumb">%breadcrumb%</div>
<br />

I think I'll move onto smarty once it gets a bit more in depth, but this has worked for me so far.

cameraman

WebmasterWorld Senior Member 5+ Year Member



 
Msg#: 3760081 posted 7:29 am on Oct 7, 2008 (gmt 0)

It's entirely subjective; there are programmers who never use it or need to use it, there's others that turn everything into an object, and there's everyone in between.

Simply, use it when you want/need to encapsulate data. Think shopping cart. The customer can be an object. A product can be an object. The cart can be an object that can hold product objects and belongs to a customer object.

OOP is most handy when you have more than one of a thing, but not only then - it's a paradigm that enables you to think of something as a thing. I have a database class. I very rarely have more than one instance of it in a script, but the class allows me to think of it in a more homogenous manner.

I don't know that headers and footers really need to be classified, but I don't think you'd go horribly awry using the opportunity as a learning tool. A header is something with which you're intimately familiar, has some pretty classic properties, and is a homogenous entity in and of itself. Not a bad test subject, IMO.

Clark

WebmasterWorld Senior Member 10+ Year Member



 
Msg#: 3760081 posted 10:28 am on Oct 7, 2008 (gmt 0)

Thanks everyone,

Nick,
I'm ashamed to say I didn't understand 100% of your code.

1. Where did you pull in the template?
2. Does this line "$output = preg_replace("/%$key%/",$page[$key],$output);" somehow use the % signs to evaluate %content% from the content as if it were a variable?

Cameraman,
Interesting. Well if there's more than one of a thing, maybe a good way to think of these as objects is to consider a page element as an object and the header/navbar/body/footer as objects that belong to the page element?

nick279

5+ Year Member



 
Msg#: 3760081 posted 10:47 am on Oct 7, 2008 (gmt 0)

Clark,

Say you have

index.php
template.tpl

in the template.tpl you'd write your html/css code and substitute %field% where you'd like to place the rendered information

in the index.php you fill in the fields by populating the $page array with the field names & data

index.php

$page['foo'] = $bar;
$page['metadesc'] = $meta_desc; //(from db)

template.tpl

<meta name="description" content="%metadesc%">
<body ....
<h2>%foo%</h2>

the preg_replace looks for, and replaces any keys in the $page array, with the corresponding value
(e.g. will ultimatley replace %foo% [in the .tpl] with $bar [from the .php])

hope it helps

p.s. apols, just above the original foreach(...
$output = file_get_contents("templates/template.tpl");

andrewsmd

WebmasterWorld Senior Member 5+ Year Member



 
Msg#: 3760081 posted 12:17 pm on Oct 7, 2008 (gmt 0)

I have been web programming for six years and the closest I have got to OOP is an object that connects to my database and that's it. To be honest I never really have understood OOP because you can have some file like functions.php with all of your functions in it and to me it is easier to call a function and pass in some parameters then to have to define a new object and then use the pointers and constructors and all of that jazz. I'm not coming down on OOP programmers I'm just saying I have never ran into a problem I couldn't solve and I never use objects. If you don't like to use objects then don't waste your time trying to implement them. It's all about your own style.

Clark

WebmasterWorld Senior Member 10+ Year Member



 
Msg#: 3760081 posted 12:36 pm on Oct 7, 2008 (gmt 0)

Thanks Nick.
p.s. apols, just above the original foreach(...
$output = file_get_contents("templates/template.tpl");

that missing piece threw me off completely! Now it all makes sense :)

Andrew,
It never bothered me either...and I've been doing web programming for 10 years...until vbulletin, which I hacked up the wazoo, "upgraded" to OOP. And all the php devs who know both, including many who used to be procedural based like you and me, after learning OOP seem to say (eventually), they never know why they didn't program that way all the time...

When I hear someone who knows both say that OOP is not better, than I'll reconsider learning this difficult step.

For me, I have to know it to understand vbulletin...but once I'm going through the motions, I want to know what the benefits are. This whole object concept does seem to make some sense.

Additionally, I'm trying to learn about object oriented databases, because I want to know more about cloud computing.

Some people are saying that relational databases don't scale as well as object oriented ones...because replicating an object without worrying about referential integrity is much easier than dealing with ever changing interlinked tables... but I still want to understand what that means exactly. What an object in an OOP database is.

I believe Google's search engine is OOP...

nick279

5+ Year Member



 
Msg#: 3760081 posted 1:41 pm on Oct 7, 2008 (gmt 0)

andrewsmd sums up perfectly for me.

I too use a lot of procedural stuff, and would have to assess each project and the reasons for/against using an OO approach.

I'm working on a project at the moment which is perfect for OO but can make it in 1/10th the time in procedural for a customer.

cameraman

WebmasterWorld Senior Member 5+ Year Member



 
Msg#: 3760081 posted 4:11 pm on Oct 7, 2008 (gmt 0)

Yes, you could look at the page anatomy that way. You can apply it to whatever degree you want - you could divide it into header, body, & footer and stop there or go all the way to html element level (a paragraph is an object etc).

Just like so many other things there are times to use OOP over procedural and there are times to forego it completely. Under normal circumstances I don't think I'd apply OOP to page elements (server-side - in javascript that's about the only way you can look at it to make the page extensible); it's just, as I said, not a bad test subject to use to learn OOP. I don't think OOP is better than procedural, it's merely another tool in your arsenal. I first learned OOP over 15 years ago in doing embedded control, but if you look at my php scripts you won't see a whole lot of classes.

As andrewsmd said, it's all about your own style, which is why I don't tell people 'you're doing that wrong' - the bottom line is whether or not it works and is future maintenance going to be an issue (a la the first response of 'when you want the code to be very hard to read'). The flipside to that is when it's part of a well-thought, well-designed, cogent app wherein it makes everything much easier to read.

Clark

WebmasterWorld Senior Member 10+ Year Member



 
Msg#: 3760081 posted 4:54 pm on Oct 7, 2008 (gmt 0)

Excellent. This thread has been very helpful to me :)

leadegroot

WebmasterWorld Senior Member 10+ Year Member



 
Msg#: 3760081 posted 9:30 pm on Oct 7, 2008 (gmt 0)

I've found the MVC model most effective.
I keep the html in plain text html (template) files and include them.
I've written code that generates standard objects for each db table, so my inserts and updates are standard, then I add the specific processing that table needs.


$theCart = new ShoppingCart('getbyCustomerID', 76);
$theCart->status = 'paid';
$success = $theCart->update();

Objects normally correspond to data, with a few exceptions. For instance, I sometimes have an object thats an element of type body, so all sorts of different things add properties to the tag.
I do have an object for the page, but it does very little - things like the title element.

Its easy to over-objectify and make the code a maintenance nightmare (where do I change X? I can't find it?!? Been there.)

For the actual question, no, I don't make my headers and footers objects. I have template files, sitting in a 'theme' subdirectory and there is no php in those files beyond checking variables exist. (ie this is the display specification and the business rules are elsewhere)

I've been really happy with this approach. Its quick to write as so much is done for me, and when I need to do maintenance there isn't a lot of head scratching.

pinterface

5+ Year Member



 
Msg#: 3760081 posted 1:22 am on Oct 8, 2008 (gmt 0)

PHP's version of OOP isn't a particularly good one, so it might be worth your time to explore how other languages do OOP (e.g., Smalltalk, JavaScript, Common Lisp) just to see what the possibilities are.

Classes in PHP are just arrays with syntax. nick279's example, for instance, is arguably object-oriented. Imagine, for a moment it were instead:

$page->domain = $domain;
$page->breadcrumb = $breadcrumb;
$page->header = $header;
$page->footer = $footer;
$output = $page->populate_template(file_get_contents($template_file));
Essentially the same thing, just with a slightly different syntax.

Or, take leadegroot's example:

$theCart = new ShoppingCart('getbyCustomerID', 76);
$theCart->status = 'paid';
$success = $theCart->update();
which isn't really any different from:
$theCart = get_cart_by_customer_id(76);
$theCart['status'] = 'paid';
$success = update_cart($theCart);
One just happens to use classes for (arguably) nicer syntax.

It's all about what jives with how you think. If you find yourself thinking "Well, such-and-such seems the easiest approach, but principles of a-popular-programming-style suggest this-or-that.", you're going too far. Stop at "easiest approach" and be done with it.

If you find yourself thinking "there has to be an easier way", start looking at alternative approaches--be they functional programming, OOP, or some other. Try them out, see what fits. Eventually, you'll develop a nose for when one style is better suited to a task than another.

cameraman

WebmasterWorld Senior Member 5+ Year Member



 
Msg#: 3760081 posted 7:07 am on Oct 8, 2008 (gmt 0)

PHP's version of OOP isn't a particularly good one
I agree. In particular, I'd really like to see multiple inheritance.

I also agree completely with the last two paragraphs. However, consider:
if($_SESSION['userlevel'] == 'user')
$user = new User($_SESSION['id']);
elseif($_SESSION['userlevel'] == 'moderator')
$user = new Moderator($_SESSION['id']);
else
$user = new Visitor();

$user->displayMenu();

Or
if($mode == 'thread')
$obj = new Thread();
else
$obj = new Post();

$obj->edit();
$obj->display();
etc.

$shippers[] = new ups();
$shippers[] = new usps();
$shippers[] = new fedex();

foreach($shippers as $shipper)
$shipping[] = $shipper->quote();

As I said, I do agree completely with the last two paragraphs, and certainly if the above represented whole scripts rather than abbreviated examples implying further manipulations then each could be accomplished in several ways without making use of classes. However, I think OO deserves a spot in a php programmer's toolbox and it's a bit more versatile than a glorified array.

nick279

5+ Year Member



 
Msg#: 3760081 posted 2:08 pm on Oct 8, 2008 (gmt 0)

I came up with 'objectise' / 'objectize' -> the process of making something OO :)

pinterface

5+ Year Member



 
Msg#: 3760081 posted 10:09 pm on Oct 8, 2008 (gmt 0)

[cameraman provides examples of object-oriented code]

Yes, writing OOP code does tend to be a lot easier when using a language's built-in facilities for it. :P

PHP_Chimp

WebmasterWorld Senior Member 5+ Year Member



 
Msg#: 3760081 posted 3:56 pm on Oct 9, 2008 (gmt 0)

JavaScript is not an object orientated language. It is a prototypical language. Hence the 'this' problem where javascript looses focus and you end up with the window object when you want something else, and the need for the call method to bring it back into focus.

I'm surprised that Java wasnt listed as an OOP language. As everything in Java is an object.

OOP code generally runs slower than procedural code. As each object is another thing that needs to be loaded into memory. So in time critical situations OOP would not be the best choice.

I seldom use OOP with PHP as generally for the sort of web interface I find procedural code slightly faster to run and not to bad to maintain. When building applications I would almost always use OOP. As there are so many different parts to the project that procedural code becomes a nightmare.

So as has been said before OOP is not always the best. It is something that you need to decide for the project.

grallis

5+ Year Member



 
Msg#: 3760081 posted 9:18 pm on Oct 9, 2008 (gmt 0)

I find Javascript's loose implementation of OOP to be annoying at best. I use JS everyday, but still can't stand it.

PHP's implementation of OOP isn't the greatest, and I agree with cameraman - I'd also really like to see multiple inheritance, but personally I find OOP easier in most situations. In smaller situations, I find it better to use procedural, but I believe anytime your code gets big or more complex, it's hands down OOP time. I switched to PHP OOP about a year and a half ago or so and haven't looked back since. But just as well, it's not good for everything.

Once you get the hang of constructing classes and dividing what goes into which class and why, I think it becomes a neater, tidier script.

Anyango

WebmasterWorld Senior Member 5+ Year Member



 
Msg#: 3760081 posted 6:43 am on Oct 10, 2008 (gmt 0)

I will tell you When to use OOP, Only to pass your OOP Exam at School ;)

Anyango

WebmasterWorld Senior Member 5+ Year Member



 
Msg#: 3760081 posted 6:45 am on Oct 10, 2008 (gmt 0)


I'm surprised that Java wasnt listed as an OOP language. As everything in Java is an object.

I think JavaScript is Object Based, not Object Oriented.

grallis

5+ Year Member



 
Msg#: 3760081 posted 7:04 am on Oct 10, 2008 (gmt 0)

Let's differentiate that Java and Javascript are two different languages for those who don't know.

nick279

5+ Year Member



 
Msg#: 3760081 posted 7:53 am on Oct 10, 2008 (gmt 0)

I keep the html in plain text html (template) files and include them.
I've written code that generates standard objects for each db table, so my inserts and updates are standard, then I add the specific processing that table needs.

leadegroot - This is exactly how I've been working for the last 3 months OO - but have hit a bit of a wall, would you mind casting your eyes over a few niggles of mine (long term niggles) :)

1. Does your 'object generation' code rerun somehow, or is it done manually? What happens when you modify a table field or add a new one and need to update the objects? Does this cause issues with the rest of the system

2. Do you have a mechanism in place for generating the means to add/edit/delete through OO - do you have some kind of form class and extend it for specific datatypes?

3. How do you handle joins / foreign keys?

Also, I've been using serialize() quite a lot recently for storing items in the DB - is working great, does anyone else use this method? I'm having success on smaller systems storing data in an array, and serializing this as I don't have to constantly modify fields in the DB. Can simply add another in the <form> code to automatically append to the DB

form
<input name="content[field1]">,<input name="content[field2]">

script
$content = $_POST['content'];
check_content($content); // iterate through array, error correct/validate etc
urlencode(serialize($content)); // or another method to upsert

Any thoughts on using this method?

pinterface

5+ Year Member



 
Msg#: 3760081 posted 6:29 am on Oct 11, 2008 (gmt 0)

JavaScript is not an object orientated language. It is a prototypical language.

Prototype-based programming is a kind of Object-Oriented Programming, and its difference from more traditional class-based OOP is precisely why I suggested JavaScript as a language which does OOP differently from PHP.

As everything in Java is an object.

More accurately, everything in Java is an object, except the things that aren't (such as primitives like int). Autoboxing doesn't really change that. I didn't suggest Java because PHP's idea of OOP is pretty similar: class-based, single-dispatch, single-inheritance.

leadegroot

WebmasterWorld Senior Member 10+ Year Member



 
Msg#: 3760081 posted 7:39 am on Oct 11, 2008 (gmt 0)

1. Does your 'object generation' code rerun somehow, or is it done manually? What happens when you modify a table field or add a new one and need to update the objects? Does this cause issues with the rest of the system

I have a chunk in the middle which I surround with comments to mark as 'don't change this section' which contains the update and insert calls, etc.
I can regen that section and paste it in for table changes etc.
Yes, thats still a bit manual, but so much better than what I used to do that I'm happy :)

Management is a cross between too complicated and too manual.
I wonder if I will end up with a system where I register file names against table names in a db table and hit a button to regen the lot - who knows :) (Thats sounds complicated and updating a class file manually has been fine so far)

2. Do you have a mechanism in place for generating the means to add/edit/delete through OO - do you have some kind of form class and extend it for specific datatypes?

I've got the early versions of that. Haven't used it much. Things tend to get refined when I use them, and this isn't getting much attention.

3. How do you handle joins / foreign keys?

So far, all my queries have been built such that there is a 'master table' in the query (to coin a phrase). That tells me which class to put it in.
Did one yesterday and didn't think it through enough - put it in the wrong class. It became obvious quickly, and was dead easy to fix.

(although I built a query yesterday that obviously didn't follow the 'master table' model and wedged it in anyway)

hope it helps :)

nick279

5+ Year Member



 
Msg#: 3760081 posted 8:08 pm on Oct 13, 2008 (gmt 0)

great response - great thread.

I really don't know how many developers are out there working on this kind of thing but it's great to meet a couple and discuss ideas.

Thx a lot for the response leadegroot - I appreciate they are pretty targetted questions and your answers are definitley helping.

Onwards and upwards!

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved