Object oriented PHP in web pages: benefits?

stndn

Golden Member
Mar 10, 2001
1,886
0
0
A while back we had a meeting in my ex-workplace regarding how we design our webpages (the backend). The meeting ended up with (among others) the decision to convert our PHP scripts into object oriented PHP.

Before that, all our scripts are scattered in its own file, and whenever we need to make use of a function (eg: Search for something), we'll include_once() or require_once() the file and use it to complete our tasks.

Now, they are starting to convert those scripts and make them into classes. So, to search for something, the current page will have to create an object of search, then call the method defined in the class.

Personally, i don't really see the benefit of doing class-based (object oriented) programming for a script (or page) that will only be interpreted as it is being read. That is, if i go to http://localhost/myscript.php, i think it's more efficient and easier to just do require_once() on external scripts and run the functions defined in that external script, instead of doing require_once() to load the class, create the object, then call the method to do the tasks.

Am i wrong in this view? Is there an advantage of doing class-based web programming in PHP? Or any interpreted language at all? Other than the inheritance of methods, i don't see anything big...

Please shed a light on this.
Thank you.


Summary:

Example: A search script needs to include external scripts to do database connection, run the search, and display the results in HTML format.

Me: When executing PHP script, just do require_once() to load external scripts, then run the functions to accomplish the task. This includes the functions to print the HTML <head>, <body>, and the page contents.

Them: When executing PHP script, it is better to require_once() classes, create an instance of that class, then call the methods defined in that class to accomplish the task. This includes the methods to print the HTML <head>, <body>, and the page contents.

Question: Any dis/advantages of class-based script execution compared to regular file-include execution? Speed? Simplicity? Use of extra resources to create objects? Others?
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
I'm not up on the differences between the old php and the oo version but I'd imagine the issues are much the same as any debate between object oriented and function based languages. OOP can make your job a lot easier from a design perspective if you know how to use it and if it is appropriate to your situation. And probably, you are going to lose some performance with objects. Whether or not that's a concern would depend entirely on the situation.

As is always the case, you should not switch just because oop is supposed to be better. The developers should truly understand the differing design philosophies if they want to switch and they'd better be sure that the result will be worth the trouble. The worst that could happen is that you get a buggier, slower, more difficult to maintain product and then everybody will hate oop because it didn't work out in your specific situation.

If the other developers really have good reasons for a switch (not "It's new and therefore cooler and better!!!") then it might be worthwhile.
 

mugs

Lifer
Apr 29, 2003
48,924
45
91
Because PHP is not a true object-oriented language, it lacks most of the benefits of OOP. The main benefits are code organization, readability and portability. As kamper noted, switching to OOP for the sake of switching is stupid. In many cases it would actually be detrimental, as it needlessly adds complexity.
 

stndn

Golden Member
Mar 10, 2001
1,886
0
0
Thanks for the responses.
Yah, i figured there's no point of moving to OOP if there's no significant gains. Especially considering it is an interpreted (scripting) language ...

One of the guys argued that he used OOP on his previous projects, and he said that it made his PHP pages loads faster after the first time of accessing the scripts. I'm not sure if it's because of the caching or if it's because PHP objects got stored in memory for future executions (that's what he said), but oh well ... whatever.

Nonetheless, i'll use a bit of OOP just for the sake of learning it, and also because i've had partial template of printing out basic html header, meta tags, footer, etc ... i might as well just use that for my pages in addition to other function-based scripts.

Thanks again -)
 

mugs

Lifer
Apr 29, 2003
48,924
45
91
Originally posted by: stndn
One of the guys argued that he used OOP on his previous projects, and he said that it made his PHP pages loads faster after the first time of accessing the scripts. I'm not sure if it's because of the caching or if it's because PHP objects got stored in memory for future executions (that's what he said), but oh well ... whatever.

That sounds suspect to me... I'd think I would have heard that before. And even if it was the case, it wouldn't cache the objects, just the code itself, and that could be done regardless of if it is a class or not. I'd wonder what his methodology was for determining that his scripts excute faster with object oriented code, and not faster with non-object oriented code. If it is the case that OOP code will run faster on successive executions, he ought to be able to find it documented somewhere.

Using OOP definitely can have benefits, but I really don't think there's a benefit to rewriting code for the sake of making it object-oriented
 

AFB

Lifer
Jan 10, 2004
10,718
3
0
I would guess it depends on what you're using the OOP for. It could make somethings much more organized with minimal slow down, but that isn't always the case (At least wasn't in 4.*) as OOP is(was) slower. As stated, switching to OOP for the sake of it is stupid.
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
Originally posted by: stndn
Especially considering it is an interpreted (scripting) language ...
Why shouldn't an interpreted language be object oriented?
 

b3b0p

Senior member
May 18, 2003
214
0
76
Are you saying that they want to output HTML code from within the class methods? That is definitely a no no. Especially if you ever want to edit your HTML code and change stuff.
 

stndn

Golden Member
Mar 10, 2001
1,886
0
0
I'd wonder what his methodology was for determining that his scripts excute faster with object oriented code, and not faster with non-object oriented code. If it is the case that OOP code will run faster on successive executions, he ought to be able to find it documented somewhere.

He said it was based on "his experience on building pages and pages of PHP scripts". And no, i didn't buy his argument, but apparently the rest of the team did.

Using OOP definitely can have benefits, but I really don't think there's a benefit to rewriting code for the sake of making it object-oriented

True that. I've had enough headache migrating our codes from $this_is_variable_name to $thisIsVariableName and other "standard naming conventions", and i'm sure glad that i'm out of the company such that i don't have to get involved with migrating function-based PHP to OO-based PHP.

I think because they have C++ and Java background (as opposed to me with C and Perl), it made them think that PHP4 is up for real OOP. Actually ... is that possible? I mean, the bias in opinion due to programming background?

I would guess it depends on what you're using the OOP for. It could make somethings much more organized with minimal slow down, but that isn't always the case (At least wasn't in 4.*) as OOP is(was) slower. As stated, switching to OOP for the sake of it is stupid.

Supposedly for the sake of code reuse, because apparently there are a few people who wants to re-use existing code but does not know how to require_once() the script that contains the function they wants to use :roll:

Why shouldn't an interpreted language be object oriented?
To be honest, i'm not even sure why i started to have that opinion stored in my mind. But here's what made me think that way.. please correct me if i'm wrong.

With interpreted language, the script is read twice: once when loading the page, to "prepare" it for execution. Then the same script is executed again to display the results. Thus, when doing OOP, the class definition will be interpreted at the first run of the script, then the object created and the class methods defined on the second run of the script.

When we want to access the method in the class, the script will have to look for the reference of the method we want to execute (eg: Is this script going to execute $objectone->print() or $objecttwo->print()? Is there any difference between the two print()?). And because of the way interpreted language works, the instances of method print() will have to be created everytime the script is executed, and the compiler will have to redo the search for which print() method to use, all over again.

With functions, there's only one instance of print(), and it will always be that one. So, the compiler does not have to go around looking for and comparing the different print() methods, like in the first case.

Am i right on this? Or should i have stayed more awake when they teach OOP and how compiler works way back in the college days?

Are you saying that they want to output HTML code from within the class methods? That is definitely a no no. Especially if you ever want to edit your HTML code and change stuff.

I'm actually thinking of using class just for printing things like the contents of <head></head>, and a few others. The same contents will be used across the pages on the site i'll be building.
The reason behind this was that i want all the pages to have the same header, CSS include, and other <head></head> contents. And whenever i make changes to one, i'll change it for all.

But now that i think about it, me wanting to do this HTML output using class (instead of just require_once 'html_header_file.php' just contradicts my own point of view above, no?

On a related note: So would you suggest i don't use any class, and just make calls to include the header texts, etc? Or make the print_header(), print_footer(), print_title(), etc ... all in one function and keep my pages as function based?


Again, thank you all for the insights -)
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
Originally posted by: stndn
Why shouldn't an interpreted language be object oriented?
To be honest, i'm not even sure why i started to have that opinion stored in my mind. But here's what made me think that way.. please correct me if i'm wrong.

With interpreted language, the script is read twice: once when loading the page, to "prepare" it for execution. Then the same script is executed again to display the results. Thus, when doing OOP, the class definition will be interpreted at the first run of the script, then the object created and the class methods defined on the second run of the script.

When we want to access the method in the class, the script will have to look for the reference of the method we want to execute (eg: Is this script going to execute $objectone->print() or $objecttwo->print()? Is there any difference between the two print()?). And because of the way interpreted language works, the instances of method print() will have to be created everytime the script is executed, and the compiler will have to redo the search for which print() method to use, all over again.

With functions, there's only one instance of print(), and it will always be that one. So, the compiler does not have to go around looking for and comparing the different print() methods, like in the first case.

Am i right on this? Or should i have stayed more awake when they teach OOP and how compiler works way back in the college days?
I see no reason to read a script multiple times. Once you build a syntax tree from the first parse you never really need to go back to the source code. I've done this for a procedural language but not for oo so I'm not sure of the details but I imagine once the code has been analyzed once there would be no correlation between object orientedness and interpretedness.
Originally posted by: b3b0p
Are you saying that they want to output HTML code from within the class methods? That is definitely a no no. Especially if you ever want to edit your HTML code and change stuff.
Good advice. Html is best written as html with as little possible interference from programmatic constructs. Client input and backend information management is another question and definitely could benefit from oo.
 

stndn

Golden Member
Mar 10, 2001
1,886
0
0
okay, so maybe using class to output plain html is a stupid idea.
but consider the following:

<html>
<head>
<title>my page</title>
<rel type="text/css" href="filename.css" />
</head>

<body>
<!-- php stuffs go here ........ -->
</body>
</html>

having the things inside <head> </head> repeated on all pages is just tiring. And that's not to mention the troubles of having to edit each and every single page whenever we decide to ditch filename.css and go with supercss.css or something... or maybe when we decide to have the default title as something else?

In any case, that was the reason for using PHP to output HTML code. It just makes life easier should one decide that the header should actually include something for all the pages on the site.

But yeah, using class might be too much in this case (just plain printing something)
Maybe i'll go back to using functions to accomplish the task.

I see no reason to read a script multiple times. Once you build a syntax tree from the first parse you never really need to go back to the source code. I've done this for a procedural language but not for oo so I'm not sure of the details but I imagine once the code has been analyzed once there would be no correlation between object orientedness and interpretedness.

if i remember correctly, my Perl teacher told us that at the first run of the script, the interpreter will ... well, interpret all the functions and variables and whatever things we specified in the script (eg: replacing the real value of $val with whatever the contents is, define the function workflow, etc). Then the script will be run through again the second time, but this time just to send the output.

So, in the case of this script:
$var = "hello world";
print "i said $var";

on the first run, line 2 will be changed to:
print "i said hello world";
and on the second run, it will do the actual print.

And since script/interpreted language is interpreted with every call to the script, i believe this extra work will have to be performed with every execution...

I might be wrong on this, though... i have to admit that i'm very bad when it comes to how compilers and interpreters work.. I only know how to read code, write code, use it, fix it, and/or break it....
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
I think a helpful guide here might be the template system that phpbb uses. I don't know if it's a widely used idea or if they invented it or what, it's just what I've seen.

What they do is have absolutlely no html in their php code. Everything is completely application logic of various forms. Then they have seperate html "templates" which contain fractions of html that will be used across different pages, or repeatedly within the same page. The application code builds all the data that needs to go into a page and then a template processor decides which templates should be used, in which order and how many times and then it goes and flushes them out, inserting relevant data as needed.

So for your case you could have a template called top_of_page like so:
<html>
<head>
<title>{$title}</title>
</head>
<body>

and you could use that for every page by specifying a title to insert. A similar template would exist for the bottom and any other elements of any page that you need. The idea is complete seperation of interface and logic code. There is essentially no duplicated html and you can even change between template sets dynamically if you want different faces to your app. I'm not saying you need to go out and copy that idea exactly (although you could get free source code for it) but it just demonstrates that you can seperate html from php without losing the ability to control various aspects of the interface.
 

stndn

Golden Member
Mar 10, 2001
1,886
0
0
Hmmm...
this thread surely has gone from OOP discussion into something else..
but i'm glad it does, because the template-based solution was going to be my next question anyway..
I'll post that question in a different thread, though, since it's about something different anyway.. probably tomorrow or next week, when i get more ahead on my programming.

In any case:

I think i've seen the templating stuffs on my PHP Cookbook before (O'reilly - good stuff). In fact, it points me to look at smarty homepage. Actually, i guess now it's a good time for me to finally go check out that site and see what it's all about..

The thing is that i'm not sure if i can install anything required for templating on my webhost, since i have no control over the include_path and whatever else is necessary...

Ideally, i would like to have the solution to be available with out-of-the-box PHP. If possible, i don't want to have to install extra things just to accomplish something.

Anyways, thanks a lot for all the information, kamper. And also thanks for everybody else in convincing me not to move from function-base to OOP. I actually would rather stay away from OOP anyway, since i am a little rusty on that section..... -(


$brain = new knowledge();
$brain->insert ("KISS, and stay with functions");
$brain->remove ("OOP");
unset ($brain);

eerrrr.... ooppsss....
 

KB

Diamond Member
Nov 8, 1999
5,401
386
126
Object Oriented could actually be harmful to code execution if used improperly. For example if one object has tons of functions in it, that don't really need such grouping, and you want to only call one of those methods, you still have to instantiate the object and the instantiation of that object will require more time/memory than just calling a single non-OOP function. I have no bencmarks to back this up, as it wold be mostly imperceivable, but theoritically this is the case.

The benefits of OOP are inheritance and polymorphism. If you won't be using these techniques, then going OOP is not the right thing to do.
 

torpid

Lifer
Sep 14, 2003
11,631
11
76
Classes that output HTML are not that bad. I don't know about PHP's capabilities, but in many OO-based web architectures you have a lot of flexibility to still write HTML and/or XML that define the user interface while also using objects. There are benefits to it, like inheritence and polymorphism, that make it really worthwhile in some apps.
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
Originally posted by: torpid
Classes that output HTML are not that bad. I don't know about PHP's capabilities, but in many OO-based web architectures you have a lot of flexibility to still write HTML and/or XML that define the user interface while also using objects. There are benefits to it, like inheritence and polymorphism, that make it really worthwhile in some apps.
Any real examples of benefits. The best one I can think of to counter your argument is jsp/servlets. Originally there were just servlets but printing html manually became such a problem that they had to invent jsps. Jsps continue to evolve so that you don't have to use any actual java code mixed with the html. When you let code and html mingle it's far too easy to embed business logic in your interface code which = maintenance nightmare.
Originally posted by: KB
Object Oriented could actually be harmful to code execution if used improperly. For example if one object has tons of functions in it, that don't really need such grouping, and you want to only call one of those methods, you still have to instantiate the object and the instantiation of that object will require more time/memory than just calling a single non-OOP function. I have no bencmarks to back this up, as it wold be mostly imperceivable, but theoritically this is the case.

The benefits of OOP are inheritance and polymorphism. If you won't be using these techniques, then going OOP is not the right thing to do.
Functions don't take up space in instantiated objects. The procedural code is stored once per class and each new instance requires only space for the data fields.

Granted, if you're creating a new object just for the sake of one method call then you don't know how to do oo properly.
 

mugs

Lifer
Apr 29, 2003
48,924
45
91
Originally posted by: torpid
Classes that output HTML are not that bad.

Not inherently bad, but bad in many cases (can limit reusability). It's pretty much common sense though when it would be bad to have the class output HTML directly, so it doesn't really need to be stated.
 

Beau

Lifer
Jun 25, 2001
17,731
0
76
www.beauscott.com
Most of my sites are in an OO format purely for logical organization and code simplification. I don't output any HTML from the objects, though. Instead, I build an XML document that is then parsed and outputed by script pages where the objects are instantiated. As far as performance hits go, I've noticed very little, if any, impact either way. (experience from running a site that gets over 20million hits per day).
 

b3b0p

Senior member
May 18, 2003
214
0
76
I thought the whole point of classes was to have reuseable code, no?

Then, having HTML in your classes nearly defeats that purpose as it is a great pain to have to edit it and makes it far less modular.

your html should go in seperate files.

classes should be left for the brains of the operation.

Using templates in php is redundent. Template engines just add extra overhead that is totally not needed. php is like a templating language in itself. It can be embedded right into the HTML which is one of its great and all powerful strengths. All while being super speedy. tell me what is the difference between the following:

<div><?php echo $content; ?></div>

and

<div>[CONTENT]</div>


 

PHP5 allows "real" OO, modeled somewhat after Java. It really helps using it. I did pics2 in PHP4 with a lot of ugly inlining and the code is a mess and impossible to maintain. pics3 is PHP5 with solid OO classes for everything. Like Beau said, you really have to separate the presentation (HTML) from the code. I am using templating (Smarty) to mock a sort of MVC pattern, with the template at the model, web as the view, and my classes as the controller.

You are really not going to see a performance hit when using OO/PHP5 vs the old functional style unless you write bad code in the first place. The Zend engine is a pretty efficient little devil. I have seen it hold up under a lot of stress.

Then again, if you are doing a little 1000-line app, there's really no need to get all into OO. A big system? Yeah, then design your classes wisely and go for it.

As for code reuse; I will be honest, don't do OO for code reuse alone. It's a good side-effect when it works, but for most web projects I find myself throwing out 75% of the code in the next project.
 

mugs

Lifer
Apr 29, 2003
48,924
45
91
Originally posted by: Beau
Instead, I build an XML document that is then parsed and outputed by script pages where the objects are instantiated.

That sounds excessively complicated... what's the benefit of doing that rather than passing the data back in variables/objects? Could you provide a context where you would use something like that?
 

stndn

Golden Member
Mar 10, 2001
1,886
0
0
Although i did find page with [l=tons of templates]http://www.sitepoint.com/forums/showthread.php?threadid=123769[/i], i'm starting to think most templating system would be redundant and will add to the page processing time.
It's probably negligible on a small site (which i'll be developing), but i'm not too sure ....

Classes that output HTML are not that bad.
Not inherently bad, but bad in many cases (can limit reusability). It's pretty much common sense though when it would be bad to have the class output HTML directly, so it doesn't really need to be stated.
does this stand the same as functions that output HTML directly?

I thought the whole point of classes was to have reuseable code, no?
Then, having HTML in your classes nearly defeats that purpose as it is a great pain to have to edit it and makes it far less modular.
But what if i'm just using the class to output ... say, the navigational menu on the left of this anandtech site.
Let's say i embed PHP code on my HTML skeleton. I'll have to copy/paste all the navigational menu on all the different pages of the site (messageview, categories, subscribe, etc), and put the PHP code on each pages.
Later on, i feel like separating programming and games into two forums, i'll have to edit all the navigational menu on each and every file, and upload them again.

Whereas if i use PHP to print the html code that controls the navigational menu (let's say i use function for that), and include the function call in each of the pages (messageview, categories, etc). When the time comes to separate programming and games forum, i'll just have to change one file (that contains the navigational menu) and that's all.

That's the way i think with regards to using PHP (class or function or just procedural) to output HTML... i'm not sure about the others.

Instead, I build an XML document that is then parsed and outputed by script pages where the objects are instantiated.
So, in a sense, you're using XML as your page template?
And i agree with mugs, it sounds complicated and intimidating...

As for code reuse; I will be honest, don't do OO for code reuse alone. It's a good side-effect when it works, but for most web projects I find myself throwing out 75% of the code in the next project.
Actually, i found myself reusing functions way more than objects/classes throughout my programming life cycle (college, work, hobby). That's probably why i never really get to be good with OOP...
I never saw the real benefits of OOP ... it's either i suck at the design, or i suck at object reuse -(

FWIW, the web hosting i have still uses PHP4. I don't think there's any that's moved up to PHP5 yet, unless it's private server?
 

Beau

Lifer
Jun 25, 2001
17,731
0
76
www.beauscott.com
Originally posted by: mugs
Originally posted by: Beau
Instead, I build an XML document that is then parsed and outputed by script pages where the objects are instantiated.

That sounds excessively complicated... what's the benefit of doing that rather than passing the data back in variables/objects? Could you provide a context where you would use something like that?

When you build a lot of websites that cater to the same basic industry/ies, it makes sense to build a common drag'n'drop framework that is easily templatable. Organizing data into logical classes that are completely separate from the design layers makes it easy to build a library of individual components that are simiple to combine in creating a new site, but you have to be able to store the resulting data into a portable format so you can use it easily. I prefer to stick to standardized technology, so I chose XML/XSL to do the templating work. The classes all output an XML element that is included inserted into the DOMXML object built by the script pages. The script pages then parse the XML doc against a specified XSL file and output the HTML -- this is really nice because I can 100% guarantee that the structure will be 100% valid.. It's really not that complicated.

Also, because all the resulting data is organized into XML, it makes it easier to reassemble it into whatever format I want for whatever exterior reason I have. I've used this method to create everything from a popular school content management system to customized flash interfaces that required very little flash-logic. Pictars is built on these methods, too
 

mugs

Lifer
Apr 29, 2003
48,924
45
91
Originally posted by: Beau
Also, because all the resulting data is organized into XML, it makes it easier to reassemble it into whatever format I want for whatever exterior reason I have. I've used this method to create everything from a popular school content management system to customized flash interfaces that required very little flash-logic. Pictars is built on these methods, too

You're releasing the source for Pictars when you complete it, right? I'll have to check it out. I have a lot to learn about XML.
 
sale-70-410-exam    | Exam-200-125-pdf    | we-sale-70-410-exam    | hot-sale-70-410-exam    | Latest-exam-700-603-Dumps    | Dumps-98-363-exams-date    | Certs-200-125-date    | Dumps-300-075-exams-date    | hot-sale-book-C8010-726-book    | Hot-Sale-200-310-Exam    | Exam-Description-200-310-dumps?    | hot-sale-book-200-125-book    | Latest-Updated-300-209-Exam    | Dumps-210-260-exams-date    | Download-200-125-Exam-PDF    | Exam-Description-300-101-dumps    | Certs-300-101-date    | Hot-Sale-300-075-Exam    | Latest-exam-200-125-Dumps    | Exam-Description-200-125-dumps    | Latest-Updated-300-075-Exam    | hot-sale-book-210-260-book    | Dumps-200-901-exams-date    | Certs-200-901-date    | Latest-exam-1Z0-062-Dumps    | Hot-Sale-1Z0-062-Exam    | Certs-CSSLP-date    | 100%-Pass-70-383-Exams    | Latest-JN0-360-real-exam-questions    | 100%-Pass-4A0-100-Real-Exam-Questions    | Dumps-300-135-exams-date    | Passed-200-105-Tech-Exams    | Latest-Updated-200-310-Exam    | Download-300-070-Exam-PDF    | Hot-Sale-JN0-360-Exam    | 100%-Pass-JN0-360-Exams    | 100%-Pass-JN0-360-Real-Exam-Questions    | Dumps-JN0-360-exams-date    | Exam-Description-1Z0-876-dumps    | Latest-exam-1Z0-876-Dumps    | Dumps-HPE0-Y53-exams-date    | 2017-Latest-HPE0-Y53-Exam    | 100%-Pass-HPE0-Y53-Real-Exam-Questions    | Pass-4A0-100-Exam    | Latest-4A0-100-Questions    | Dumps-98-365-exams-date    | 2017-Latest-98-365-Exam    | 100%-Pass-VCS-254-Exams    | 2017-Latest-VCS-273-Exam    | Dumps-200-355-exams-date    | 2017-Latest-300-320-Exam    | Pass-300-101-Exam    | 100%-Pass-300-115-Exams    |
http://www.portvapes.co.uk/    | http://www.portvapes.co.uk/    |