Slashdot Mirror


Advanced PHP Programming

sympleko (Matthew Leingang) writes "PHP5 has hit its third release candidate, so get used to the idea of using it. George Schlossnagle has written a great book on PHP programming which ought to generate some enthusiasm. But it's not just about PHP5: the book includes great information on everything from coding style to high-level problem-solving. I met George through a friend of mine who works for the Developers Library, and I'm glad to have finally gotten a look at his book." Read on for Leingang's review of Advanced PHP Programming: A practical guide to developing large-scale Web sites and applications to PHP5. Advanced PHP Programming: A practical guide to developing large-scale Web sites and applications to PHP5 author George Schlossnagle pages 609 publisher Sams Publishing (Developers Library) rating 9.999/10 (I don't give perfect scores) reviewer Matthew Leingang ISBN 0672325616 summary See subtitle

Many of the previous generation of PHP books were fattened with lots of filler: how PHP imports form-submitted variables into its namespace, definitions and examples of valid XML documents, one-line summaries of every PHP function, even an HTML reference. It's like going to Gallagher's Steak House and filling up on free bread. Ladies and gentlemen, may I submit the Atkins-Friendly PHP book. This is not a book about syntax or data structures. This is a book on how to use PHP in enterprise environments. During my first read, I realized around page 126 that I had already learned as much as I had expected to learn and I was just getting started!

The book is very well written, with a friendly tone that is neither pedantic nor partisan. A knowledge of PHP before version 5 is assumed, and the situations tackled are very much from the real world. The focus goes beyond getting what you want to appear in the browser, too; scaling problems of very large web sites, managing a code base with multiple developers, and building your own extensions to PHP are all discussed.

The author draws most examples from a Unix + Apache + PHP environment, and MySQL is the primary database used. The examples are all in PHP5, but many ideas can still be implemented in PHP4. In other words, you can still learn a lot even if you're committed to PHP4 for the near future.

Part I of the book is called Implementation and Development Methodologies (some of these part and chapter names could be a little less clunky, even if they are correct), and the first chapter is about coding style. After that comes a thorough discussion of the new features of PHP5. These are language aspects that are commonplace in other object-oriented languages (e.g., java and python), but which I admittedly knew little about:

  • encapsulation: the ability to keep object attributes and methods private or protected;
  • static attributes and methods to make class functions or singletons;
  • user-definable constructor, destructor, accessor, mutator, and copier functions;
  • interfaces, which are like abstract classes. A class can implement one or more of these as well as extend a concrete class;
  • exceptions, which allow propagation of errors and warnings back up through the function stack.

Other PHP programming concepts are discussed in this part, such as templating, using the command-line interface, and unit testing. The chapter on Managing the Development Environment includes some CVS basics as well as how to organize and keep separate your development and production environments without breaking what works. Another topic discussed is when to use PEAR classes and when to roll your own.

Part II, Caching, is where the book gets hard-core. Once your application works, how do you optimize its performance and scale it so you can have hundreds of thousands of users?

  • You can use static variables to reduce recalculations, and compile your regexps.
  • You can cache data on the PHP level in flat files, DBM files, shared memory, or even in user cookies.
  • There are also solutions outside of the PHP userspace. The ordinary PHP process takes the text which constitutes the programmer's code and compiles into a assembly-style intermediate code. Then the intermediate code is executed. If a script is executed several times without change, the same intermediate code is created, executed, and thrown away several times. A compiler cache saves this intermediate code and reuses it. The author has developed a free, open-source compiler cache.
  • There are also code optimizers, which eliminate dead code and overly-verbose constants.
  • Reverse proxies also work in web sites to reduce network latency. Latency occurs when a server is stuck waiting for a request to be completed before it can execute. A reverse proxy server only collects requests, then hands them off on a high-speed network to the actual server.
  • This can be made even better with content caching. The proxy can determine if the request requires handling by the PHP webserver at all. If a stale, cached copy suffices, it is served instead.
  • Content compression sends your data over the internet compressed. The client's browser is in charge of decompression.

Part III, Distributed Applications, is of big importance to the developer of medium-sized sites. The author discusses the familiar topics of database interaction (including how to troubleshoot your slow queries), authentication, and session handling. Then a chapter on clustering: how to arrange multiple, redundant servers to create a robust, fail-safe system.

The final chapter in this part covers another hot topic: Web Services. Say you want to edit your weblog entries on a real text editor rather than through a web form. If you have RPC (Remote Procedure Calls) set up on your web server, you need only write a script which manufactures a request to a web service and and ships it out. What's the sales rank on Amazon of the book you just wrote? What's the weather like in Medford, Massachusetts today? These are all jobs for web services. XML-RPC and SOAP are approaching the standards state of usage, so using one of these means you don't have to develop your own RPC client or server library. SOAP is even richer than XML-RPC: it's an all-purpose messaging protocol which is in use by many of the big players in web services (e.g., Amazon, Google).

In Part IV, Performance, the author returns to the optimization question. How can PHP scripts themselves be made to run faster? There are several techniques:

  • Use the apache benchmarker or other load-generating programs to determine which requests take the most time.
  • Use a PHP profiler such as the one the author has written to examine your script line-by-line and determine which function calls are most expensive.
  • Use a synthetic benchmarker (such as the one included in PEAR) to analyze small bits of code and discover how efficiently they do their task. Which is faster: interpolation of variables or string concatenation (the latter, at least before PHP 4.3)? If you don't have a library compiled into PHP, can you implement all the functions in userspace efficiently (not really)?

Part V, Extensibility, is for people who want to adapt PHP on the language level for their needs. This part requires a knowledge of C and a strong grip on your hat! After a discussion of PHP and Zend Engine (the virtual machine on which compiled PHP runs) internals, the author shows how to make both simple and complex extensions. You can add new functions to PHP, add a suite of library wrappers, add and manipulate classes and objects, all using pre-defined macros. In the last chapter, you can extend Zend itself to (say) implement all errors as exceptions, create a PHP Shell, an opcode-dumper, or modify the author's compiler cache or profiler.

I very much enjoyed the book. I have chosen to take the plunge into PHP5 for a new web project, partly because this book convinced me it's worth it. I can't imagine I'm going to use everything I've learned from the book, but I'm glad to know how problems like these are solved.

There are a few typos and misspellings, but that's to be expected in such a large book with limited turnaround time. Definitely recommended.

Matthew Leingang is a Preceptor in Mathematics at Harvard University. He continues to try to integrate web development into his day job. You can purchase Advanced PHP Programming: A practical guide to developing large-scale Web sites and applications to PHP5 from bn.com. Slashdot welcomes readers' book reviews. To see your own review here, carefully read the book review guidelines, then visit the submission page.

21 of 189 comments (clear)

  1. php-embed by SIGALRM · · Score: 5, Informative

    Part V, Extensibility, is for people who want to adapt PHP on the language level for their needs

    This is an often-overlooked advantage in PHP: the ability to use php-embed to run embedded PHP within another application. For example, our company has created an HL7 HIPAA-accelerator in C/C++; we chose PHP as the embedded language in our product--by which users can create custom data transformations.

    The reason? PHP is easy to use, loosely-typed (which is an advantage in our project), fast, and of course, free. It was a great decision.

    --
    Sigs cause cancer.
    1. Re:php-embed by SIGALRM · · Score: 4, Interesting

      It's not really a mod, just a php_embed.c and php_embed.h which wrap up some TSRMLS functions, not much documentation on it, but a decent thread here.

      --
      Sigs cause cancer.
    2. Re:php-embed by dinodrac · · Score: 5, Informative

      Hmm... A first post that wasn't a troll. I'm amazed.

      I've got a couple database applications using PHP that I've been working on for a while - I wasn't aware that PHP could be easily embedded into a C application.

      Obviously, I'd get better performance with a hybrid of C and PHP code, so this actually simplifies quite a few projects for me. (No more mixing PHP, Perl, C, Python, MySQL and TCL on a single application - yay! ;)

      Thanks for pointing this out..

    3. Re:php-embed by nkh · · Score: 4, Informative

      Why not Lua or Ruby? They can both be embedded easily (and Lua has even been used in Monkey Island 4). Were there other advantages for PHP?

    4. Re:php-embed by SIGALRM · · Score: 4, Informative
      Thanks for pointing this out..

      Sure. One more thing, the zval integration is easy as pie, something like:

      zval *zarray;
      MAKE_STD_ZVAL(zarray);

      if ( array_init(zarray) == FAILURE ) {
      // ... something wrong
      }

      add_assoc_string(zarray, str_name, str_val, 1);

      ZEND_SET_SYMBOL(&EG(symbol_table), str_tokenlevel, zarray);

      Forgive the poor code above, just the way I remember it... I'll email you the php-embed stuff I have in its entirety.
      --
      Sigs cause cancer.
  2. most of the books by joeldg · · Score: 4, Interesting

    most of the books don't cover the topics of cli-based php which is unfourtunate.
    Things like php-ncurses and php-gtk or even how to properly debug cli apps and it is strange saying there is a large following of PHP commandline (cli) people out there.

    Anyway, always good to see more books at any rate.

  3. Latest software by Ford+Prefect · · Score: 5, Interesting

    PHP 5? Great!

    I've got a bit of a complaint about computer books, in that they frequently concentrate on the latest and greatest versions and brush aside the older versions - the versions that the majority of web hosts might be running, for instance.

    I was looking for a MySQL book a while back, and there were dozens of them on the shelves in the bookshop, but all based around MySQL 4 - not the ubiquitous MySQL 3 that I was trying to learn. Looking through at all the new features can be a bit dispiriting, especially when you're stuck with the older version.

    Anyone else had similar problems?

    --
    Tedious Bloggy Stuff - hooray?
    1. Re:Latest software by zapp · · Score: 4, Insightful

      Isn't that why we have used books? Ebay, Amazon, Half.com. I'm sure somewhere you can find a book for an older version of a piece of software.

      --
      no comment
  4. Mysql + Apache 1.x by john_smith_45678 · · Score: 4, Insightful

    Sigh, I really wish these books would get with the times and start using PostgreSQL (or even Firebird) and Apache 2.x (I assume the book uses Apache 1.x since the PHP developers seem so against 2.x).

    1. Re:Mysql + Apache 1.x by john_smith_45678 · · Score: 4, Informative

      I've been told by the Apache crowd that the Prefork MPM obviates any concerns of thread safety in libraries.

      I've been using 2.x for about a year. Zero problems. Performs great.

    2. Re:Mysql + Apache 1.x by Percy_Blakeney · · Score: 5, Informative
      I can't think of a single reason to prefer PostgreSQL over it, in fact.

      I used to think that, until I realized that my programs were twice as complicated as they needed to be due to MySQL's lack of typical relational database functionality. Triggers, views, sub-selects, user-defined functions, transactions, templates... the list of PostgreSQL advantages (feature-wise) over MySQL is long.

      MySQL is now trying to catch up to PostgreSQL in the feature category, but is still not even close. That's not to say that MySQL is worthless -- quite the contrary: if you want an indexed file system, MySQL is the way to go. On the other hand, if you want a good, open-source relational database, PostgreSQL is a champ.

      Ease of use pushed us away even before we looked at benchmarks, which are all triumphantly in MySQL's favor.

      PostgreSQL is a bit harder to initially set up, when compared to MySQL. On the other hand, it isn't rocket science; it is still pretty simple.

      In terms of benchmarks, you might want to notice that MySQL is hardly "triumpantly" winning normal benchmarks. Take a typical MySQL table (MyISAM) and try doing lots of concurrent reads and writes. You'll find that MySQL's habit of locking the entire table on writes really is a downer when it comes to performance.

      Another thing to note is that MySQL has placed their libraries under the GPL, making them somewhat incompatible with the PHP license. This has caused a bit of a rift in the PHP community, with the result being that MySQL will probably be less supported by the PHP developers while PostgreSQL increases in support.

    3. Re:Mysql + Apache 1.x by ahodgson · · Score: 5, Informative

      The major performance advantage MySQL claims over PostgreSQL in real world use is small queries executed in a primarily read-only environment. MySQL also performs deletes and updates very fast, in a single-user environment.

      Locking issues cause MySQL to slow down greatly when the database is shared between readers and writers. In fact, any significant amount of concurrent write traffic has, IME, always caused MySQL to deadlock.

      My own testing showed that MySQL, on a dual P4-2.4 with PHP could deliver about 630 pages/second with 1 very simple query per page. PostgreSQL delivered 480 pages/second with the same page. This is MySQL's optimum environment and it only beat PostgreSQL by 31%. Certainly something to consider, but hardly earth shattering.

      Since PostgreSQL is so much more capable in every other way, it wasn't hard to decide to move everything to PostgreSQL.

  5. Re:Advanced PHP programming by imroy · · Score: 5, Funny

    I think we can add this title to the list of contradictory terms:

    • Military intelligence
    • Microsoft Works
    • Advanced PHP programming

    :)

  6. Re: Against Apache 2.x? by Anonymous Coward · · Score: 5, Insightful

    This seems to be a really common misconception among readers of slashdot. The truth is this:
    - PHP developers are not opposed to Apache 2.x.
    - PHP is stable on Apache 1.3 _AND_ 2.x.
    - Apache 2.x has a large number of new features designed to better handle high volume sites (with or without PHP)

    MySQL is still the standard web-hosting provider database backend, that is why most books cover it. mySQL is very similar to other SQL dialects. If you understand SQL, PostgreSQL is easy and you shouldn't need explanation on how to run queries from PHP. The books focus on PHP, not the SQL languages... if you want to learn about SQL, get a SQL book.

  7. "Advanced" PHP ? by bunnyman · · Score: 5, Funny

    Isn't that called "Perl?"

  8. Quit your elitist bitching by PeeAitchPee · · Score: 5, Insightful

    There are times when to use a strongly-typed, "true" OO language like Java or C++ and times to use a scripting language like PHP or Perl. Part of being a good programmer is being smart enough to use the right tool for the right job. If you want to torment yourself by over-engineering a small- or mid-sized website in EJB, go for it, but respect those who like being able to get stuff up quickly and easily, with a minimal learning curve. And YES, it is possible to build secure web apps in PHP, despite what you may have heard.

    When you've only got a hammer, everything looks like a nail.

  9. Language Bashing by sfhc · · Score: 4, Insightful
    I wish people would get over language bashing.

    The issue is not weather PERL or PHP or C is better than the other.

    Languages are just tools. Writing good software is a reflection of one's ability to plan, use OOP, and troubleshoot code, just to name a few.

    When faced with a problem that needs solved, you examine the problem, and select the most appropriate tool(language) to get the job done, and hopefully you apply good software writing skills to the solution.

    Even if you think PERL or something is so much better than PHP, but you suck at writing good software, your software is going to suck.

  10. I have a problem with PHP's scope by randallman · · Score: 5, Insightful

    PHP was originally developed to make web programming easier in the same way Bash makes certain operating system tasks easier. PHP:Web::Bash:OS.
    PHP5 is impressive, but it appears to be trying to change its scope and here is why. Like Bash, PHP is a big time saver for small programs, but is more difficult to write and maintain as the program gets larger and more complex. The features added to PHP5 will let it scale better, but it will lose its Bash-like advantages. It is trying to move into the arena with Java, ASP.Net(?Maybe), Python, Ruby, ... The problem is you can't have both Bash-like scriptablity and Java-like power/maintainability. So PHP will take the road of Visual Basic -> VB.NET.
    After seeing MY limits with PHP I moved to Python although I still use PHP for simple web scripts. In my opinion, PHP5 is a new language in an old arena. You should choose the right tool for the job, and if you need the new features in PHP, have a look at a powerful, weathered language like Java, Python, or Ruby, or (add your language here).

  11. Re: Against Apache 2.x? by Mr.+Slippery · · Score: 4, Informative
    If you understand SQL, PostgreSQL is easy and you shouldn't need explanation on how to run queries from PHP.

    You ought to be using PEAR's DB class anyway, which abstracts away most of the differences in dialect.

    --
    Tom Swiss | the infamous tms | my blog
    You cannot wash away blood with blood
  12. Good for SysAdmins too! by LojaK · · Score: 5, Informative

    I am a sysadmin by profession, working at a mid-sized ISP in Toronto. I chose to be a sysadmin because I don't really enjoy programming -- but the nature of the job dictates that I code to improve efficiency or functionality. Recently I had to work on an in-house web application, and I chose to do it in PHP, but quickly found that the relatively small webapps I've worked on in the past were not much preparation, so I bought this book..

    To borrow a phrase, "in a nutshell", this book is excellent! Some of it is beyond my skills at the moment, but I appreciate every bit. The author covers OO in a way that I understood, and presented real-world solutions that helped me understand. But, IMO, the best part isn't the PHP, it's the operational theory -- the real problems that sysadmins and web programmers face with large websites, caching, load-balancing, scalability. This made the book worth the $80CND I paid for it.

    I highly recommend it!

    -- Steve.

  13. Re:Making fun of php? by agwis · · Score: 4, Insightful

    "It's just absurd. They really don't take into account the target marked for the solution. And the current system setup is running just fine and dandy without any trouble. Should the number of visitors increase ten-fold (which it never will), well... Add some slave database servers and more webservers. Suddenly you have the board of directors going: -Uhm, why didn't you write the system in Java. We hear Java is a good thing. Java is scalable. Java is more secure."

    I've encountered this a few times myself but I have a different view point on it. I agree that many sites will never grow enough to worry about scalability but the one thing that does almost always happen is new features being added.

    I've personally seen a few PHP sites that run flawlessly but they are not easily extendable. They are written in such a manner that developers are afraid to work with it because it's too easy to break stuff, or adding new features will involve rewriting big chunks of code. I will admit that I've seen this in other programming languages as well such as .asp and .jsp/java.

    If you consider programming styles such as struts, cocoon, webwork, etc. which encourage the MVC pattern it makes huge difference in the maintainability of web applications down the road. I find that java applications tend to use either these types of frameworks or custom ones that follow the same idea while I find many PHP applications are more like spaghetti code that do work fine but are a nightmare to add to in the future. They are quickly built but the lumping of PHP code in HTML makes it hard on projects where designers need to update the look and feel of a website but have no idea how to change their pages without mucking up the code.

    I'm not saying that is the case all the time but what I am noticing is that PHP is gravitating towards OO programming and seems to be encouraging the separation of business logic from presentation logic, which is a very good thing. The argument that PHP is not as scalable as Java really should be more like PHP is not as extensable or maintainable as Java, but this certainly seems to be changing for the better.