Want to read Slashdot from your mobile device? Point it at m.slashdot.org and keep reading!

 



Forgot your password?
typodupeerror
×
Book Reviews Books Media

PHP In Action: Objects, Design, Agility 232

Michael J. Ross writes "Despite being perhaps the most popular Web language in use, PHP has for much of its history been criticized for not offering the full capabilities of object-oriented programming (OOP). But with the release of version 5, PHP introduced a robust object model, and made it easier for its proponents to create well-architected Web sites and applications. In turn, the new OOP capabilities have facilitated additional best practices, such as design patterns, test-driven development, continual refactoring, and HTML templates. These topics and more are explored in the book PHP in Action: Objects, Design, Agility."
PHP in Action: Objects, Design, Agility
author Dagfinn Reiersol, Marcus Baker, Chris Shiflett
pages 552
publisher Manning Publications
rating 8/10
reviewer Michael J. Ross
ISBN 1932394753
summary A pragmatic guide to object-oriented PHP development.
Authored by Dagfinn Reiersøl, with Marcus Baker and Chris Shiflett, the book was published on 3 July 2007 by Manning Publications, under the ISBNs 1932394753 and 978-1932394757. Its subtitle accurately reflects the major themes of the work: creating PHP applications built upon objects, utilizing Web-oriented design patterns, and incorporating agile programming techniques such as refactoring and test-driven development. Also covered are methods for effective form handling, database extraction, date and time representation, and more.

As a result of trying to adequately cover such a large number of major topics in a single book, the amount of material is considerable, and the book is certainly longer than the typical Web programming book in general, and PHP book in particular. Spanning 552 pages, the material is organized into 21 chapters, grouped into four parts: In Part 1 ("Tools and concepts"), the authors discuss PHP 5, its strengths and weaknesses, and how well it can be used with advanced programming principles; an overview of objects, exception handling, and references; visibility, abstract classes, and interfaces; effective use of classes and object-oriented design; inheritance, composition, and more on interfaces; advanced object-oriented principles; six design patterns that are especially appropriate for Web-based systems (Strategy, Adapter, Decorator, Null Object, Iterator, and Composite); and lastly, date and time handling using objects.

For developers well-versed in OOP, Part 1 may be more of a review, while Part 2 ("Testing and refactoring") could be the most valuable portion of the book. In the four chapters, the authors dig into the details of test-driven programming, refactoring, and Web testing. These chapters and all that follow take a very pragmatic approach to conveying ideas, which is consistent with the theme of Manning's "In Action" series, based upon the idea that programmers tend to learn best by reading sample code instead of generic discussion. For instance, test-driven development (TDD) is demonstrated by showing how to implement database transactions, a contact manager, and e-mail functionality. Mock objects and top-down testing are illustrated through the creation of an e-mail class, and further extended with a discussion of faking the mail server. Given that testing is the primary theme of the entire part, one might expect a more lengthy discussion of TDD, but Reiersøl correctly notes that this particular book is not trying to replace the many manuscripts and articles already published on agile development; also, the database examples adequately demonstrate the general principles discussed prior. The chapter on refactoring is well worth reading, and touches upon the controversial topic of how much one's PHP code should be separated from the HTML code — a topic later revisited in the chapter on templates. Also explored is a topic critical to maintenance programmers — refactoring versus rewriting. Two different testing frameworks are discussed, PHPUnit and SimpleTest; the latter is used throughout the book. The final chapter in this part explains how to test Web pages programmatically, by faking interaction, and other techniques. The chapter ends with a section providing steps on how to deal with "the horror of legacy code," when the unfortunate programmer has inherited a nightmare of a live Web site.

The third part of the book, "Building the web interface," begins with an examination of templates, the arguments for and against them, and three of the most commonly used template engines: Smarty, PHPTAL, and XSLT. One of the previously discussed design patterns, Composite, is utilized for combining templates to create complex Web pages. The chapter on user interaction makes use of the Model-View-Controller architecture, with the subsequent chapter delving deeper into the topic of controllers for Web pages. The next two chapters cover an area of site development that is a frequent cause of uncertainty, "bandage coding," and security risks: user forms and input validation. The book's coverage of the PEAR package HTML_QuickForm, alone makes it worth reading. Part 3 concludes with a chapter on abstracting database resources through objects and the Singleton pattern.

The fourth and last part of the book ("Databases and infrastructure") is relatively brief, comprising two chapters on marrying SQL with object orientation. The authors present a number of techniques for shoehorning SQL transactions into object-based code, including encapsulating queries inside of methods, building SQL statements dynamically, substituting SQL elements such as column and table names, using SQL aliases, and using SqlGenerator.

It is clear that the lead author, Dagfinn Reiersøl, has put a tremendous amount of time (three years, as noted in the preface) and effort into creating this work. The discussions are wide-ranging and in-depth, and there is just enough sample code to illustrate the ideas being discussed and also break up the visual monotony. The illustrations are limited in number, and consist mostly of class diagrams and UML sequence diagrams. Overall, the treatment of each topic clearly reveals that he has considerable experience with them, and has given thought to the pros and cons of some possible approaches, though not all of them.

However, there are still some weaknesses in the book. For example, in all of the material discussing how to separate the SQL code from the PHP code, I found no mention of stored procedures, such as those made possible in MySQL. All of the sample code appeared to be solid, though there was no clear reason for the inconsistent use of print() versus echo() is different code samples. All of the chapter summaries could be excised without any loss of value, and many of the chapter introductions could be eliminated as well or condensed.

On a more mechanical level, the book had many minor weaknesses: It was not encouraging to see the first erratum even before reaching page 1: "raising own level" on page xix, in the second paragraph. Readers may initially be confused by such attributions as "Uncle Bob [Uncle Bob]" (on page 77). In a future edition, it should be explained that names in square brackets are biographical references listed in the Resources section, which follows Appendix B. In the first sentence in Chapter 12, the reference to "Jackass" will probably be confusing to many readers — particularly non-Americans — and is not in the best of taste. In the text and the table of contents, the chapter and part titles are written in sentence case, instead of title case, for no obvious reason. It is not clear whether this is meant as an unsuccessful attempt at literary hipness, or just an unfortunate reflection of the current text messaging generation, which is eschewing rules of grammar that for centuries have made text easier to read. Finally, there was one problem in the production of the book, and not its writing: Several of the pages had light brown spots on them that were apparently part of the paper, and not a result of post-production staining. But these may be limited to my particular (brand-new) copy of the book.

Readers interested in learning more about the book could start at the publisher's Web page, which features an online table of contents and index, all of the book's source code, two sample chapters (7 and 21) in PDF format, and a link for purchasing the electronic version of the book, also as a PDF file. Any road/code warriors who do development on their laptops, on the go, will appreciate having this book readily available.

Yet most of these objections are minor and easily fixable, and do not detract from the value of this book. I especially liked the depth of experience brought to each topic, and the authors' consideration of differing viewpoints. PHP in Action is a competent, engaging, and detailed discussion of object-oriented and agile programming principles that can help PHP developers boost their effectiveness and the quality of their code.

Michael J. Ross is a Web developer, writer, and freelance editor.

You can purchase PHP in Action: Objects, Design, Agility from amazon.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.
This discussion has been archived. No new comments can be posted.

PHP In Action: Objects, Design, Agility

Comments Filter:
  • by wellingtonsteve ( 892855 ) <<wellingtonsteve> <at> <gmail.com>> on Wednesday January 23, 2008 @02:24PM (#22156930)
    Cue the PHP vs Every Other Language debate..
    • Re: (Score:2, Funny)

      by Anonymous Coward
      Visual Basic is so much better than PHP.

      Discuss.
      • Re: (Score:3, Funny)

        by Anonymous Coward
        I do all my scripting in Logo.
      • If you're using VB.Net, it can be a lot better than PHP. First the .Net framework is a lot more easier to user than the 80,000 functions all under the same namespace of PHP. I also like that it's strongly typed, and compiled, but that's just personal preference. VB.Net is basically C# with different syntax. Also, Visual Studio is much better than any IDE I've ever seen for PHP. VB.Net isn't perfect, but I personally find it quite a bit easier to work in than PHP.
    • Re: (Score:3, Informative)

      by gambolt ( 1146363 )
      I've been playing with Keppler, a Lua web stack. It's surprisingly robust for how easy it is to get started with.

      http://www.keplerproject.org/wiki/US/HomePage [keplerproject.org]
    • Re: (Score:2, Insightful)

      by Anonymous Coward
      For all the criticisms about PHP, I won't bite the hand that feeds me. It's widely available, easy to work with, in demand, and best of all, FOSS. I'm a businessman and a web designer, not a computer scientist. I think that anyone who gripes about PHP's shortcomings is just wasting their breath: It's not going away, it's been used for very large sites (see Facebook, Wikipedia, GoDaddy, etc.), and most of us find it to be a really great tool. It's not as though PHP gets in the way of developing with [insert
  • by bigtrike ( 904535 ) on Wednesday January 23, 2008 @02:40PM (#22157212)
    This looks like a great book for those of us already stuck with PHP. For the rest, I'd suggest avoiding it entirely. PHP 5's OOP is still pretty awful and still has many caveats which have simply never existed in other languages. For example, the exception handling is pretty useless as it generates "Fatal error: Exception thrown without a stack frame in Unknown on line 0" when used in a number of contexts.
    • Stuck? (Score:2, Insightful)

      Get over it. PHP is not perfect, but it does a damn good job. If it didn't, it wouldn't be so widely used. You can respectfully disagree, but try to maintain some civility here instead of suggesting we all just avoid PHP as if it's some kind of curse. There isn't a tool in the world that doesn't have it's flaws.

      I've been using PHP for eight years and there hasn't been a day where I wished I had chosen another language. Sure, I wish the PHP of today was available eight years ago, but I can't complain with
      • by Anonymous Coward
        PHP: Because 10 million newbies can't be wrong.
      • Re:Stuck? (Score:5, Interesting)

        by LuckyStarr ( 12445 ) on Wednesday January 23, 2008 @03:10PM (#22157714)

        I've been using PHP for eight years and there hasn't been a day where I wished I had chosen another language. Sure, I wish the PHP of today was available eight years ago, but I can't complain with what is available now.
        That makes me wonder what other languages beside PHP you know.
      • Re:Stuck? (Score:5, Funny)

        by Samus ( 1382 ) on Wednesday January 23, 2008 @03:12PM (#22157748) Journal

        Get over it. GWB is not perfect, but he does a damn good job. If he didn't, he wouldn't be so widely loved. You can respectfully disagree, but try to maintain some civility here instead of suggesting we all just avoid GWB as if he's some kind of curse. There isn't a tool in the world that doesn't have his flaws.

        I've been praising GWB for eight years and there hasn't been a day where I wished I had chosen another president. Sure, I wish the economy of eight years ago was available today, but I can't complain with what is available now.
        Just a parody. I'm not trying to turn this thread political. Laugh or don't laugh then move on.
      • Re: (Score:3, Insightful)

        by dubl-u ( 51156 ) *
        Get over it. PHP is not perfect, but it does a damn good job. If it didn't, it wouldn't be so widely used.

        Yes, all things that are popular are good and work well! Windows 3.1 and Visual Basic were very popular. So was the belief that the earth is flat. And there's chlamydia. That's hella popular.

        I've been using PHP for eight years and there hasn't been a day where I wished I had chosen another language.

        No offense, but if you've been using the same language for eight years without any regrets, I don't see y
        • Re: (Score:3, Informative)

          No offense, but if you've been using the same language for eight years without any regrets, I don't see you as having enough perspective to offer up much useful information.

          So my career path, which lead to developing in a specific language, has somehow excluded me from being eligible to offer up any "useful information"? Where is the logic in that?

          As far as I can tell, PHP is popular because it's perfectly adequate language for cranking out some basic dynamic pages, and it's very easy to learn and s
  • PHP5 (Score:5, Interesting)

    by corychristison ( 951993 ) on Wednesday January 23, 2008 @02:41PM (#22157224)

    But with the released of version 5, PHP introduced a robust object model, and made it easier for its proponents to create well-architected Web sites and applications.
    ... PHP 5 was released ~2.5 years ago. It MUST be noted that there were some significant changes in the 5.2.x branch. I don't see any mention of PHP 5.2 in this review. This book is already dated.

    I do web development & design for a living. I use PHP because it is what I got into and I have not yet had the time and/or drive to really try anything else. PHP is so available and that is its real strength. It's biggest problem is those lazy folks who are still running 4.2.x or some branch that is or is to be discontinued very soon here. As well there are some known exploits and issues in the older branches.

    I love the rapid-ness of PHP though. At present I even use PHP-GTK2 to prototype all of my idea's while I learn new languages. That is, I'll make a rough draft in PHP-GTK and then try to do the same in C/C++... which is much more painstaking for someone who has used web development for so long. But I am slowly un-learning my habits to depend on magic to handle memory for me, etc.

    Yup. Just my random bablings.. I am sure there was a reason I started writing this comment.
    • PHP is so available and that is its real strength. It's biggest problem is those lazy folks who are still running 4.2.x or some branch that is or is to be discontinued very soon here.

      You kind of contradicted yourself there. That, or PHP is much more pervasive than I give it credit for, such that even the 5.2.x branch is more widely deployed than everything else... but I kind of doubt that.

      I love the rapid-ness of PHP though. At present I even use PHP-GTK2 to prototype all of my idea's while I learn new la

      • Not all of it makes you handle your own memory -- but you absolutely should have that experience of having to do that, so that you understand what's going on behind the scenes (why not to slurp the whole file, etc).

        Agreed. Even PHP developers should know about memory management. I use PHP all the time, I love it. But it can be just as dangerous as any other language. Functions like file_get_contents() are extremely convenient but also extremely stupid. It's kind of similar to C's strcpy() (only it won't cau
      • You kind of contradicted yourself there.

        I don't quite see the contradiction there, perhaps it was the way I worded it? What I meant to get across was that PHP 5.2 is the current stable branch and that there are some hosts out there that are still strictly only PHP4... despite some of the security issues.

        You know, there's quite a lot besides PHP and C/C++. Not all of it makes you handle your own memory -- but you absolutely should have that experience of having to do that, so that you understand what's g

        • What I meant to get across was that PHP 5.2 is the current stable branch and that there are some hosts out there that are still strictly only PHP4... despite some of the security issues.

          True, but it still contradicts the point you made that it's "so available". Maybe it's how I'm reading it, but I took that to mean that every cheap web host in the world is going to have PHP somewhere -- but that's not much of a strength if you're counting all the PHP4 hosts in that statistic.

          it allows a lot of control and

    • I haven't used php in years. Can you link to a page that highlights the significant changes in 5.2?
        • Thanks. I found those from google earlier, but when I read over those lists I don't see anythign that jumps out as somethign that would make the book different or that would warrant coverage. Which of those things are really cool new features? Did any change the way you do things?
          • There wasn't anything that broke my code, however there have been a lot of enhancements (such as the changes in Datetime - in the upgrade guide link) which really speed up development. More extensions and improvements.. most of which involve OOP stuff.
      • I haven't used php in years. Can you link to a page that highlights the significant changes in 5.2

        Did you even TRY to look for it yourself? I haven't used PHP in years either, yet I just went to php.net and right there in the second news entry on the front page, it announced 5.2.5 is released, and contains a link for Changelog for PHP 5. Boy that was hard.
        • Yes, I did exactly that. However, the OP made it seem that there were some significant changes in 5.2 that somehow either made the book out of date or were so cool that they deserve mention in the book. Looking at the change log did not reveal such changes which is why I asked. Context is important my friend!
    • by BerntB ( 584621 )

      I use PHP because it is what I got into and I have not yet had the time and/or drive to really try anything else. PHP is so available and that is its real strength. It's biggest problem is those lazy folks who are still running 4.2.x or some branch that is or is to be discontinued very soon here. As well there are some known exploits and issues in the older branches.

      PHP's advantage is an easy learning curve, so it is easy to pickup (no cheap jokes about fat women, please). Larry Wall described [perl.com] that as [

    • You're telling me.. while I'm not a fan of PHP, it does have it's uses, and is reasonably suited as a web development language/platform... I've always disliked the fact that most libraries for it are very C-Like, with everything being a global method... I will say it's very hard coming from a web development platform, even object/event driven ones, and work in a GUI world.. the extend of my gui development tends to go as far as configuration/automation tools, and not really much more...

      Which is funny, b
  • by Anonymous Coward on Wednesday January 23, 2008 @02:41PM (#22157226)

    <?php
    function foo(){ return array(1=>'a', 2=>'b'); }
    echo foo()[1];
    ?>

    Parse error: syntax error, unexpected '[', expecting ',' or ';' in ... on line 3
    wtf?
    • by corychristison ( 951993 ) on Wednesday January 23, 2008 @02:52PM (#22157408)
      While what you may have not exected, there are many ways around this... the most simple of which:

      <?php

      function foo($get)
      {
      $array = array(1=>'a', 2=>'b');
      return $array[$get];
      }

      echo foo(1):

      ?>
      Which, in reality is cleaner in the first place. :-)
      • by Azarael ( 896715 ) on Wednesday January 23, 2008 @03:03PM (#22157576) Homepage
        If foo() is explode() or something similar though, you're out of luck. I expect that this is what the OP was referring to.
        • by muszek ( 882567 )
          bringing the luck back to you, mate:

          function my_explode($delimiter,$string,$key) {
            $array = explode($delimiter,$string);
            return $array($key);
          }
          echo my_explode('.','a.b.c',1); // b
      • Re: (Score:3, Informative)

        by nuzak ( 959558 )
        No, it's not cleaner in the slightest. Now you can't get at the whole array. Unless you want to overload the function. All that boilerplate because the designers of PHP still don't pay attention to basic things like this.

        Another workaround is to just use a temporary. Or a different language outright.

    • Why would you expect that to work? That's just lazy programming. Using another few chars to assign what the function returns to another var isn't going to kill you, and the bytecode will come out the same.
      • by mibus ( 26291 )

        Why would you expect that to work? That's just lazy programming. Using another few chars to assign what the function returns to another var isn't going to kill you, and the bytecode will come out the same.

        Why shouldn't it work? Yes, I'm lazy - I don't want to write an extra line in and have to think about a new name for a temporary variable, when I don't actually need the variable.

        I can't count how many times I have code like this:

        $row = mysql_fetch_array(mysql_query('SELECT COUNT(*) FROM mytable'));
        $theco

        • I have to admit, I'm kind of glad that PHP doesn't let you do that. This is kind of a Perl-ish mindset, that everything that can be consolidated should be. It makes for dense code. I'll take PHP's limitations here, as they seem to be a bonus for readability.
    • by thue ( 121682 )
      test.php
      <?php
      function f() {f();}
      f();
      ?>

      t@t ~> php test.php
      zsh: segmentation fault php test.php

      I had some fun with that when I accidentally introduced it while developing, and the webserver suddenly kept serving up blank pages.

      PHP catches almost all other kinds of user errors, and shows a nice error message, but when I reported this one they referred me to the manual and marked the bug report BOGUS. I still maintain that the interpreter crashing is not expected behaviour.
  • yeah right (Score:3, Insightful)

    by mrsbrisby ( 60242 ) on Wednesday January 23, 2008 @02:56PM (#22157436) Homepage

    PHP has for much of its history been criticized for not offering the full capabilities of object-oriented programming (OOP).
    Yeah, that's exactly why it's criticized. It has nothing to do with the fact it takes them three releases to fix a simple integer overflow, that they thought "safe_mode" was an access control system, that "require" pulls in files unexpectedly from malicious sites. It has nothing to do with the fact that mysql_connect() takes arguments, and programmers are encouraged to use mysql_connect() in a way that makes it incompatible with the default mysql install. It has nothing to do with the fact that regular expressions are so prevalent and yet there is no syntax for them. It has nothing to do with the fact that the language mutates drastically with toplevel global configuration variables.

    Seriously, it has nothing to do with the fact we're sick and tired of cleaning scripts written by people who don't know what they're doing, and we like blocking access to your site for major vulnerabilities. We actually love it how when your script gets owned, you don't notice for months because you do the development on the server, all the while jerkoffs are udp-flooding from your site. Because you'll never pay for this usage, and you'll expect us to fix your script, it doesn't matter because we're just really upset that it isn't "offerring the full capibilities of object-oriented programming".

    That and we sometimes wonder what it would be like to fling poo...
    • by SirSlud ( 67381 )
      That and we sometimes wonder what it would be like to fling poo...

      Well, there's always the option of becoming a Perl developer. ;)
    • by rho ( 6063 )

      Sure, and those are all valid complaints.

      Yet PHP continues to be used by some of the most popular sites. Why is that?

      I think because PHP *is* easy and approachable, and so when some guy has an idea for something he just starts building it. He doesn't have to hire a Java programmer at $80K a year to tell him how his idea is not going to work.

      • Yet PHP continues to be used by some of the most popular sites. Why is that?

        Worse is better [jwz.org].

        I think because PHP *is* easy and approachable, and so when some guy has an idea for something he just starts building it. He doesn't have to hire a Java programmer at $80K a year to tell him how his idea is not going to work.

        That's an interesting way to look at it.

        I would look at it differently: If I wanted to be successful, would I use the same tools that all those unsuccessful people are using? Or would I use the

  • As a complete programming noob looking to get into web-related design and things of that nature, what languages are good to start with and to branch to other languages? Would that be like C-> PHP -> SQL? What other languages apply and/or in what order are languages needed to learn to start to bring things together for well designed websites?
    • by Azarael ( 896715 )
      These days you can insert Python and quite a few other languages into the middle slot (D also comes to mind). I'd suggest just doing some searching around the net to see if you can find something that suits you.
    • Definetly learn SQL. You will need it. PHP is easy enough to learn and you can start making dynamic web apps quickly. You do want to find some good books and sites that discuss PHP programming. You don't need to know other languages.
      • And definitely ignore all the tutorials on the web and avoid mysql_ functions. Use PDO. It lets you do paramterized queries which is the actual correct way to guard against sql injection, along with increasing speed. Using PDO will also let you switch to another database without changing every line in your database code. You may still need to tweak some queries, but at least you won't have to change every line of code.
    • by nuzak ( 959558 )
      Java. Yes, it's a craptastic language, but you wanted web development, and until you at least know something about JavaEE, if only to have educated reasons to hate it, a good chunk of potential clients see you as swimming in the kiddie pool. Plus, you get to branch to other languages that are actually a pleasure, like Scala.

    • by avi33 ( 116048 )
      Well, I hate to go back to the dreaded car analogy, but C -> PHP -> SQL is a bit like saying you should learn mechanical engineering before you learn to change the oil in your car, then learn how to back it out of the driveway.

      If you have nothing but brains and time, C will be a great start...managing references vs. pointers and memory...you will be bulletproof when you start using a 21st century language. Not to start a flamewar here, but maybe it's useful in plenty of ways (mostly learning how freak
    • by Phrogman ( 80473 )
      Despite its naysayers - and hey this wouldn't be slashdot if you mentioned a programming/scripting language and dozen people didn't immediately post about how bad the language in question was - PHP is an excellent introduction to web-based programming. Sure, there are other approaches you can take, which may even be far better, Ruby, Python, Java etc, but with PHP you can accomplish something and start learning in very short order and there is still a lot to absorb. I think its a good way to learn programm
    • I have developped web services with Perl, PHP, C#, Java and I tried Python for fun.

      If you don't know HTML, Javascript CSS learn them First.

      I'd certainly consider PHP as a good starting point...Why?

      - You can easily play with PHP on most Linux distribution without any difficulties. Most of the time PHP is part of the default web server package. (same for Perl but usally it requires additionnal installation like DBI if you want to play with database)
      - Syntax is quite simple and almost as flexible as Perl (almo
    • As a complete programming noob looking to get into web-related design and things of that nature, what languages are good to start with and to branch to other languages? Would that be like C-> PHP -> SQL? What other languages apply and/or in what order are languages needed to learn to start to bring things together for well designed websites?

      Stop looking at languages that way. They aren't like spoken languages- you cannot realistically speak one well enough to make up for the fact you can't speak any o

  • by Maxmin ( 921568 ) on Wednesday January 23, 2008 @02:59PM (#22157498)

    PHP introduced a robust object model, and made it easier for its proponents to create well-architected Web sites and applications.

    While I agree with the latter overall, I dispute "robust object model." What's missing? Polymorphism is sketchy, and static initializers are missing, for two. In PHP5, you can only initialize static properties with literals or constants - no function or method calls.

    Also, calling up the inheritance chain, to a grandparent class's implementation of a method, is difficult to say the least.

    While PHP5 is a *lot* better than PHP4 (and probably Perl if one took the time to compare) - it's not really comparable to truly robust OOP languages such as Java, Smalltalk and C++.

    Mind you, I code in PHP5 for a living. It gets the job done, but it has to be called on its limitations, and you gotta be honest and tell programmers who want OOP from PHP5 that it has limits, and how to work around them. None of this "robust object model" stuff.

    • While PHP5 is a *lot* better than PHP4 (and probably Perl if one took the time to compare) - it's not really comparable to truly robust OOP languages such as Java, Smalltalk and C++.

      How is it better than Perl?

      I'll admit Perl's OOP is weird. It's weird syntactically, it's weird conceptually, it feels bolted on, etc.

      But scratch the surface a bit -- it's also every bit as powerful as Java or C++. Moreso, I'd say, especially if you like "duck typing" (to steal a Ruby term).

      • by Maxmin ( 921568 )

        For coding, I find PHP5's syntax clearer - verbose keywords are the key, for me. For usage, I find Perl's better - simply require/use a module, instantiate, use, etc. Plus, the CPAN archive of modules and classes is outstanding.

        However, I feel about Perl's OO the way I feel about Javascript's - it's syntactically weird, as you say, and not verbose enough for me. Too much implied through context and operators, not enough spelled out. That said, I tough it out and work with 'em both.

        For Javascript, sy

        • by tknd ( 979052 )

          Too much implied through context and operators, not enough spelled out.

          There's nothing stopping you from being more verbose in perl.

          For example I typically write my plain functions like this:

          sub add($$) # (x, y)
          {
          my $x = shift;
          my $y = shift;

          return $x + $y;
          }

          While I could have easily gotten away with:

          sub add($$) { $_[0] + $_[1]; }

          which actually turns out to be faster but not very easy for the unexperienced to read or maintain.

          As such I reserve non-verbose and awkward code for special situations (needs optimization, needs to go fast) but I tried to be verbose

          • I generally prefer something like:

            sub add {
            my ($x, $y) = @_;
            return $x + $y;
            }

            However, the one-line example you listed is the kind of thing I might use as a callback. Sometimes, I just can't resist overly-clever, completely unreadable one-liners.
    • by nuzak ( 959558 )
      > static initializers are missing

      I come to bury PHP with a backhoe, not to praise it, but: why on earth does it actually need static initializers? PHP code runs as a script. You just stick the initialization code in the script.

      • by Maxmin ( 921568 )

        Haha - well, that's a good point, but one I won't concede due to my long-lived habits. =)

        Some static properties you only want to initialize once, and they're not singletons or the like, so you don't necessarily want to trigger their initialization through the constructor. I suppose you could wrap the static initializer code in another static method, then call that method from the bottom of the .php file that defines the class. I have a recollection that there are problems with that.

    • by Bob9113 ( 14996 )
      Mind you, I code in PHP5 for a living. It gets the job done, but it has to be called on its limitations, and you gotta be honest and tell programmers who want OOP from PHP5 that it has limits, and how to work around them. None of this "robust object model" stuff.

      As a long-time OO programmer who has been baptized by fire over the past two months in PHP, I strongly concur with your sentiment. PHP is another good tool to have in the tool box, and the OO is decent but a little short of full-blown. Your suggesti
  • by SanityInAnarchy ( 655584 ) <ninja@slaphack.com> on Wednesday January 23, 2008 @03:00PM (#22157530) Journal

    PHP has for much of its history been criticized for not offering the full capabilities of object-oriented programming (OOP).

    Nope. PHP has been criticized for:

    • starting out as insecure by default
    • lacking the basic capabilities of most other languages -- not just OOP, but things like anonymous subroutines
    • being designed around the need to embed code in a template (not a good idea -- separate content from logic from presentation!)
    • having essentially nothing compelling to offer once other languages got said templating ability -- but sensibly as an add-on, not as a core feature of the language (all PHP files, even library code, must be sandwiched between <?php and ?>)

    I could go on. Not all of these are really legitimate complaints, or a reason not to use the language; indeed, it has evolved. Due to the amount of code that exists in PHP, and the amount of cheap hosting which runs some form of PHP, I can no longer accuse people of being stupid for choosing PHP, although I might call them insane for liking it if they've given anything else half a chance.

    But I wouldn't put a lack of basic OOP particularly high on the list, especially with how dysfunctional the OOP was when it was finally added.

    Disclaimer: As much as I enjoy flamewars, and although I realize this will feed one, that's not why I'm posting. I'm just posting to clarify -- if you thought all PHP needed was OOP, you're dead wrong. If you're trying to improve PHP, look beyond OOP. (Look especially to the mysql_add_slashes_no_really_i_mean_it_this_time() functions, and compare them to Perl's support for prepared queries.)

    • but they *do* have anonymous functions, with the create_function() call.
      The annoying thing is though that the function will not get cleared from memory once if goes out of scope, making it leak memory. great.
    • You mean like mysqli_stmt_prepare ?
      http://us2.php.net/manual/en/function.mysqli-stmt-prepare.php [php.net]

      Looks pretty much like PERL's version
      http://articles.techrepublic.com.com/5100-3513_11-6139247.html [com.com]
      • Pretty much.

        I should have been clear -- a lot of the criticism of PHP is for historical reasons. But they are kind of valid historical reasons, because a lot of people do still code like that.

        But you can probably build a decent API on top of most Turing-complete languages.
  • I've used Smalltalk, C++, Java, Python etc. 1st time experience using PHP in real OO dev with phpUnit. I have enough pain with PHP language defects that remind me with the pain with C++. This is my wisdom, use PHP carefully like C++ as there are a lot of language traps behind the close door. The biggest defects is the array comparison. I think PHP is doing copy-on-write behind the scene; but the lacking of way to compare the object identity is a real pain. Both '==' & '===' are fooling. There are
    • by nuzak ( 959558 ) on Wednesday January 23, 2008 @03:32PM (#22158104) Journal
      I remember the the discussion on IRC that lead to the creation of the === operator. The designers of the language (back when they hung out on IRC) actually did not comprehend the concept of "object identity". I had to eventually resort to calling it a pointer compare, at which time I was told "PHP isn't C, it doesn't have pointers". That was pretty much the end of PHP for me.
  • Publisher web site (Score:3, Informative)

    by Anonymous Coward on Wednesday January 23, 2008 @03:07PM (#22157646)
    Maybe a ./ editor can fix the link in the article for the rest of us ;-)

    The publisher link in the article should have been: http://www.manning.com/reiersol/ [manning.com]

    Thanks in advance
  • by Tablizer ( 95088 ) on Wednesday January 23, 2008 @03:30PM (#22158056) Journal
    a robust object model, and made it easier for its proponents to create well-architected Web sites and applications.

    I've never seen good examples of OOP making websites or typical business clearly better. Any bad non-OO coding presented was merely poor knowledge of procedural, bad specific languages, or lack of knowledge about good relational techniques. I challenge anybody to clearly demonstrate OOP being better for the mentioned domains.

    I've found flaws with the OO books out there. For one, they assume unrealistic change patterns to artificially boost OO. And please no anecdotes; for those are not dissectable. If OO fits your own personal psychology better, that's fine, but I don't wear your head.
         
    • 1) maintainability
      2) understandability
      3) code reusability
      4) loosely coupled code
      5) modular code

      If you don't understand how these can be helpful in business and heavy web applications, you've probably never worked on one with a team before..
      • I have to laugh. I was just having a conversation with a Java/Swing guy and everything you list is precisely what what's missing from the modern "OO" environment.

        Yes, I agree, as a concept, well written OO can provide those things that you mention:

        1) maintainability
        2) understandability
        3) code reusability
        4) loosely coupled code
        5) modular code


        Then again, *any* well written code provides those things. What we see, however, is ever growing heaps of interdependent class libraries who's periodic API deltas cause
      • I just want to comment on

        2) understandability

        This actually is a result of a self fulfilling prophecy of sorts. No one, to my knowledge, has ever demonstrated that OO was inherently more understandable than other methodologies. But I do not dispute your point in the context of the other points you bring up, for in a sense, it is true.

        The reason...

        It appears to me that colleges all bought into OO. And so they churned out a vast number of graduates who all spoke the OO language. And so if you hire people,
        • OO on a basic level is more difficult to understand than a procedural equivalent

          That's probably true. But a nail gun is also more complex / difficult to understand than a hammer. The reason it's chosen as the tool of choice by professional carpenters is that it's much more powerful.

          OOP does seem to be a double-edged sword, though. While well-written object-oriented code can be substantially easier to read and understand than well-written procedural code, badly written OOP code can be harder to understand and more complex than badly-written procedural code. So no, it's not exactly

          • by Tablizer ( 95088 )
            While well-written object-oriented code can be substantially easier to read and understand than well-written procedural code,

            Please show me a single example in the domains mentioned.
                 
  • PHP and the web (Score:5, Insightful)

    by mlwmohawk ( 801821 ) on Wednesday January 23, 2008 @03:41PM (#22158236)
    PHP, or "Personal Home Page" to us old time users (Not PHP Hypertext Processor, as some revisionists would have to believe.) is a simple web scripting language first envisioned in the 90s for making simple web pages.

    For what it is, PHP is pretty good, a quick and dirty scripting language that, if used right, can make some pretty impressive applications.

    The real problem with PHP is the bickering and infighting little boys club that is the PHP development community. Over time they've learned a lot, but for the most part they believe they know everything and everyone else is wrong. Even though there are public forums, decisions are made on IRC chats. It is not as transparent or well functioning as groups like Apache, PostgreSQL, and others. A lot of petty crap goes on behind the scenes and a lot of people who would have been active contributors get pissed off and leave.

    I could go on with first hand and second hand stories and it is my opinion that it is this lack of professionalism that hinders PHP quality and adoption on an enterprise level.

    All that being said, PHP has a solid purpose in the web world. Java and .NET environments, and things like JSF or Swing are HUGELY complex and difficult to manage. With a continuum between simple HTML docs to HUGE applications, PHP sits in a very wide middle ground that it easy to manage and deploy.
  • I chose to work with PHP due to its flexibility. Writing software by creating types is useful in certain places, but I have found that it tends to require more code to be written than is needed for most web applications. Many of the applications which I currently maintain have been written elegantly using basic GET and POST checking and a series simple of functions.

UNIX enhancements aren't.

Working...