• DC PHP Conference Slides Oct 20, 2006

    Posted by Mike Naberezny in PHP

    Slides from my DC PHP Conference talks are now available:

    Special thanks to my friends Chuck Hagenbuch, Matthew Weier-O’Phinney, and Paul M. Jones for their feedback and help preparing the talks.

  • Upcoming Talks Sep 11, 2006

    Posted by Mike Naberezny in PHP,Ruby

    The nice folks behind the DC PHP Conference asked me to put out a note to let you know I’ll be speaking there, so here’s a bit about the talks I’ll be giving and other events I’ll be attending in the next couple of months:

    DC PHP Conference (Oct 18-20)

    • PHP Intranet Web Services is a new talk that is geared to fit into the conference’s theme of “integration with the federal government”. PHP is an excellent glue language for integrating web services and legacy applications on intranets and there are a host of libraries available to help. We’ll explore some of these options and talk about the unique aspects of developing PHP-based services behind corporate firewalls.
    • Getting Started with Zend Framework will give developers a jumpstart on developing with the Zend Framework. A brief introduction will include installation, an architectural overview, comparing it with alternatives, and explaining its process and online resources. We’ll then dive right into some of the more useful components through examples with sample code. I’ve been around the Zend Framework longer than most so feel free to bring all of your questions for Q&A and code for possible hacking sprints later.

    Zend/PHP Conference 2006 (Oct 30 – Nov 2)

    • Best Practices of PHP Development will be an extensive three-hour tutorial session. Matthew and I had such a good time speaking at the last Zend conference that we’re doing it together again this year with a new tutorial session. We’ve both been working as professional PHP developers for many years and this is our chance to share some of the PHP development and deployment tricks we’ve learned along the way.

    Other Events

    Since starting my own consulting business, I’ve also been having a great time doing quite a bit of Ruby on Rails development in addition to my usual Python and PHP programming and training. As I dip into Ruby more, I’ll be attending the Pragmatic Studio (Oct 9-11) and also the Rails Edge Conference (Nov 16-18).

    If you’re headed to any of these events, contact me if you’d like to meet up or if you have any requests for the talks.

  • Zend Framework Tutorial Published May 2, 2006

    Posted by Mike Naberezny in PHP

    The April 2006 issue of php|architect is now available. This issue marks my first appearance in their pages with the cover article, “Introducing Zend Framework”.

    In the article, I begin by introducing Zend’s motivations for creating a framework and how it relates to their PHP Collaboration Project. More information on these topics can be found on the Zend Framework website. I then dive into a tutorial where I take a business scenario and show how the components included in the Zend Framework can be put to work.

    The article demonstrates a workflow where invoice data is retrieved from a web service, an invoice in PDF format is then built from that data, and finally the resultant file is emailed to a customer. The components Zend_XmlRpc_Client, Zend_Pdf, Zend_Mail, and Zend_Search_Lucene are explored along the way.

    I’d like to thank the team at php|architect for such a professional and enjoyable experience getting the article to print.

    Update: The article is now available for free download in PDF format here.

  • Zend Framework Manual Updated Mar 13, 2006

    Posted by Mike Naberezny in PHP

    For those of you who are interested in browsing the Zend Framework manual online, I’ve made some improvements to the interface that will make it more enjoyable: http://framework.zend.com/manual/

    There’s no question that the excellent manual at php.net is a big reason that PHP is so easy to use. We recognize this and documentation has been very important to the Zend Framework project from the first day. We aim to always have the highest quality documentation possible, and to make it as accessible as possible by publishing it in multiple formats.

    The distribution currently ships with the documentation in HTML for offline viewing. In the near future, we plan to publish a PDF version as well. There will be many future updates to the website and we plan to also add search capabilities (powered by Zend_Search, of course).

    Documentation is currently available only in English, although already some users have volunteered translations of parts of the manual. After we reach the 1.0 release and the docs stabilize, we’ll begin building our documentation team to do as many localizations as possible. If you’d like to help the Zend Framework succeed in your home country, helping with translations will be a great way to contribute to our effort in the near future.

  • Zend Framework 0.1.2 Released! Mar 8, 2006

    Posted by Mike Naberezny in PHP

    I’ve just rolled out Preview Release 0.1.2 of the Zend Framework, less than a week since its initial release. We’ve received many great emails and there is now quite a growing community on the mailing list. Thanks to all that are participating by sending in bug reports and feature requests. We’re also excited that several community members have already stepped up and are working on new contributions for the framework. We’ve even begun receiving translations for the documentation.

    In addition to the new community participation, several of our commercial partner companies are working on refining existing code and preparing new components. I hope that the next preview will also include some of this new work, as well as promoting Zend_Search_Lucene from the incubator.

    Preview Release 0.1.2 includes bug fixes, the unit test suite, and additional documentation. Please see the changelog below. The new version can be downloaded from here: http://framework.zend.com/.

    We hope that new releases will become a very frequent event and I encourage you to get involved on the mailing list and send your feedback.

    Zend Framework                                                 NEWS
    |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
    =RELEASE 0.1.2 / 8-Mar-2006=
    - Unit test suite is now included. (Mike)
    - Docs for Zend_Controller are now included. (Mike)
    - Coding standards were out of date. Reported by Steph Fox. (Mike)
    - Fixed default charset in Zend_Mail constructor.
      Reported by Jakob Buchgraber. (Mike)
    - Fixed several Zend_Filter methods. (Chris)
    - Fixed JSON datum encoding.  Reported by Edwin Vlieg. (Mike)
    - Fixed FormRadio Helper.  Reported by AJ Tarachanowicz. (Chris)
    - Fixed Zend_Uri_Http to work with new Zend_Filter. (Chris, Mike)
    - Docs for the Zend_Db::factory() method were incorrect.
      Reported by Dinh. (Chris)
    - Zend::loadClass() now works inside __autoload().
      Reported by Rob Allen. (Mike)
    - Fixed notices from Zend_Pdf_Element_Dictionary.
      Reported by Ralf Eggert. (Alex)
    - Fixed notices from Zend_Search_Lucene_Index_SegmentWriter.
      Reported by Jared Williams. (Alex)
    - Removed defunct Zend_Db_DataObject docs. (Mike)
    - Added NEWS.txt file (Andi)
    
  • MashupCamp Feb 23, 2006

    Posted by Mike Naberezny in PHP,Python,Ruby

    Earlier this week, I spent two days at MashupCamp. This great event was held at the Computer History Museum in Mountain View, California.

    Mashups are an interesting topic. “Mashup” is one of those terms like “Web 2.0” that’s trendy and really hard to define in any concrete terms. Basically, mashups are taking two or more web service APIs (or data somehow gleamed from the web) and then building a useful application by combining them.

    The caliber of developers that attended was top notch and this could easily be seen by the great apps that were demonstrated. These were the kind of folks that know XML inside and out, know everything annoying about SOAP headers, know XHTML strict better than HTML 4, and can tell you the method signatures of the services they use from memory. Every developer that I talked with had experience with at least two scripting languages, usually more. It was a great crowd with some very smart and talented people in attendance.

    Mashups themselves tend to get put together very quickly. Sometimes people get an idea and implement a mashup in a few hours or a few days. It was great to be around so many developers who really grok the newest web technologies and know the fastest ways to develop applications to take advantage of them. So, what were they using to get things done fast? Besides the mashups themselves, that’s what I was interested in learning about.

    It turns out these developers were really pragmatic. They use what works and gets their job done the fastest without getting in the way — even if that means Perl. I don’t mean Catalyst or any other kind of fancy frameworkish thing, I mean straight Perl CGI. If you read the blogs these days, you’d think Perl is almost dead for web applications. I counted four mashups using Perl in some way. The most common application was backend processing but I saw one using it on the frontend as well.

    Three mashups that I saw were using Python. One of them was built on the Twisted asynchronous framework. I’ve done some work with Medusa but haven’t worked on a project needing all the power of Twisted yet. It certainly looks impressive. Another Python mashup was the excellent chicagocrime.org website, built on the Django framework by its co-creator Adrian Holovaty. A lot of people I talked with at MashupCamp were interested in Python, especially at the Googleplex where I attended an afterparty (thanks, Adam!). Several Googlers told me Python is Google’s standard scripting language and were quick to mention that Google recently picked up Python creator Guido van Rossum. Of course, everyone reading his blog already knows that.

    Ruby has a nice buzz going these days and it wasn’t surprising that it made a showing as well. I counted one mashup using it, powered by Ruby-on-Rails, although it was sort of a joke by a PHP 5 developer (the author of TagCloud). I heard that there was another Ruby-based mashup there but to my knowledge it wasn’t demoed. Coming from more of a Python background, I spent quite a bit of time with a couple of the Ruby developers at the conference to see what they liked best about the language and why they’d picked it over Python. I’m not sure that they drew any significant conclusions but they were down-to-earth and really nice guys. One of the Ruby users was also telling me about Nitro and seemed particularly enthusiastic about Og. A company called Rubyred Labs brought some nice grapefruit.

    ASP.net had a presence with one mashup using it. As with the Zend PHP Conference, I did get some nice freebies from Microsoft and noticed all the coffee cups said “Microsoft” on them. The coffee wasn’t bad, either. Visual Studio was given out as one of the prizes. I’ve already got my copy and you can download Express online.

    Java didn’t make a showing as far as I saw, although Stephen O’Grady noted one that I apparently missed. However, there was an appearance by Johnathan Schwartz who gave away a T2000 server.

    PHP was unquestionably the language of choice for developers at MashupCamp. I counted thirteen mashups using it. I made a point to talk to as many PHP developers as I could and nearly everyone had moved to PHP 5, although some were still supporting customers with legacy PHP 4 code. I believe nine out of the thirteen mashups powered by PHP were on PHP 5, with at least one more in transition. Most of the mashups were built within the past few months, or in many cases, the past few weeks. Everyone seemed very excited about PHP 5 in general.

    Amongst all of the hi-tech showings at this event, I have to say that the highlight for me was definitely meeting Bob Frankston. Bob, together with Dan Bricklin, developed the world’s first spreadsheet for microcomputers: Visicalc. This might be showing my age but it was truly an honor to meet this tech luminary and chat with him about the first generation of microcomputers, the 6502 microprocessor, Commodore computers, and everything in between. Thanks, Bob. I won’t soon forget it.

    All in all, it was a great event and I’m looking forward to the next one.

  • Symfony Templates and Ruby’s ERb Feb 19, 2006

    Posted by Mike Naberezny in PHP,Ruby

    After hearing the podcast, I went over to the Symfony website to check it out. I haven’t downloaded Symfony yet but I did watch this screencast. One thing that I think Symfony gets right is that it appears to use partitioned PHP code for its templates, in the spirit of Paul‘s Savant system. Putting all the “Smarty vs. Savant”-type arguments aside, the resulting templates in Symfony are nice and look very much like ERb (.rhtml) as it is used by Ruby-on-Rails. I think the ERb templates are a bit cleaner. However, it doesn’t have to stay that way.

    In Ruby, instance variables are accessed with @var_name. This is the same as self.var_name in Python or $this->var_name in PHP. If the template’s variables are scoped as instance variables of a class such as in Savant, and short_open_tag is disabled, the resulting PHP syntax can be a bit unwieldy:

    var_name ?>
    

    Compare this to the succinct but equally powerful ERb:

    <%= @var_name %>
    

    I noticed in the Symfony demo that there is no separation of scope between variables passed to the template from the controller and local variables in the template. In the screencast, $products in the template comes from the controller and is indistinguishable from the local variables $id and $title. I’d like to see them scoped properly ($this->products) but I can certainly understand why they did it this way. Using $this-> in the template everywhere quickly gets messy.

    One solution to this problem is to enable short_open_tags and then give the nod to Ruby by overloading PHP’s silence operator (@) to $this-> in the templates. This gives a very similar syntax to ERb:

    
    

    Using the silence operator in this way won’t break syntax highlighting in the IDEs, since this is legal PHP syntax on its own. The silence operator would not normally prefix a dollar sign, so keeping the dollar allows us to distinguish between normal code that should be silenced and when the operator is overloaded to $this->. Templates should never be doing operations that need to be silenced anyway.

    The syntax shown above is much shorter and more convenient but there appear to be two problems with this solution. First, relying on short_open_tag is a beginner’s mistake in PHP since it’s not enabled on all installations. Second, it’s not practical on most installations to install an extension to do this overloading.

    Fortunately, there is an easy solution to both of these problems. At some point, the template engine must include() the templates for PHP to execute them. A stream wrapper can be registered to rewrite the @$ into $this-> and also expand short tags if short_open_tag is not enabled. The result is a short snippet of pure PHP code that gives this syntax and should also run on the majority of installations.

    Here’s the proof of concept (PHP 5).

  • pecl/operator and Other Neat Stuff Feb 1, 2006

    Posted by Mike Naberezny in PHP

    Sara Golemon‘s newest extension, pecl/operator, seems to have quietly slipped under the radar. This extension adds operator overloading support to PHP 5. I don’t think operator overloading fits the “PHP spirit” and as such I speculate it probably won’t ever make it into the core. Regardless, it’s interesting that this extension is now available and certainly makes for some fun experiments, especially if you’re already familiar with techniques from languages like C++.

    Here’s a very simple example for demonstration:

    class N {
      public function __add(N $x) {
          return new N();
      }
    }
    var_dump( $n1 = new N()   );  // object(N)#1
    var_dump( $n2 = new N()   );  // object(N)#2
    var_dump( $n3 = $n1 + $n2 );  // object(N)#3
    

    As you can see above, pecl/operator adds some new magic methods. There’s no documentation yet, however you can see the list of new methods by browsing the source for the extension. It’s relatively short and, for the most part, the new methods are intuitively obvious from the names.

    Remember the debates over a String class on php-internals? With pecl/operator, you can do some fancy things on your own in userland. There’s many possibilities of what you can do with this, so go have some fun. Users on UNIX-like operating systems can compile the extension as usual. Windows users will be pleased to find binaries over on Edin Kadribasic‘s excellent pecl4win.php.net site.

    On a somewhat related topic, I’ve read a fair number of posts from PHP bloggers lately who are discovering languages like Ruby and commenting that metaprogramming (self-modifying code) isn’t “possible” in PHP. You can do some very powerful things with another extension from Sara: pecl/runkit. Even in vanilla PHP, you can also do some nice tricks by include()ing runtime-generated code through the stream functions. These, combined with PHP 5’s object overloading capabilities, make PHP a pretty rich environment for all sorts of hackery. It’s not that metaprogramming isn’t possible in PHP, it’s just non-obvious or inconvenient. Most of these ideas are not applicable to solving everyday problems but it’s always interesting to try your creativity and push the limits.

    Millions of programmers lead very productive and expressive lives without things “missing” in PHP like metaprogramming, lambda functions, and mixins. However, everyone is talking about them these days and understandably so — they’re neat. There’s a great deal of other neat stuff in different languages out there to inspire you also. Whether or not all of these things, including pecl/operator, are necessary or even desirable for everyday web development is a continuous debate. However, what’s not easily debatable is that learning a new language or even just reading about one can only serve to broaden your experience, give you new ideas and ways to approach problems, and make you a better PHP programmer for it.

  • __get(): An Alternative to __autoload() Jan 8, 2006

    Posted by Mike Naberezny in PHP

    __autoload() is a magic function introduced in PHP 5 that provides a mechanism for on-demand loading of classes. After its inclusion in PHP, many argued that using such a feature is too magical or not a good design practice. Putting the religious debates over the appropriateness of __autoload() aside, its implementation does have one significant drawback: it is a function declared in the global scope. Once a function is declared, it cannot be redeclared. This means __autoload() can’t be used effectively in shared libraries, since any other code could have already declared it.

    Similar lazy-load functionality can be achieved on the class level by using __get() as shown in this example:

    class Test {
      public function __get($offset) {
          switch ($offset) {
              case 'obj':
                  // include() and instantiate $obj here or elsewhere.
                  // Set $this->obj so we never hit __get() again.
                  return $this->obj = $obj;
              default:
                  throw new Exception("Unknown property $offset");
          }
      }
      public function testLazyLoad() {
          $this->obj->test();
      }
    }
    

    In the code above, $instance->obj is initially unset. When testLazyLoad() first tries to access it, __get() is called and the object is then loaded and instantiated. Before returning, $instance->obj is set, so subsequent accesses won’t have the overhead of the __get() call. This behavior is somewhat analogous to that of __autoload().

    A downside is that $instance->obj will have public visibility, which may or may not be a problem depending on your application of the technique. Perhaps a small advantage is that while exceptions cannot be thrown from __autoload(), they can be thrown from __get().

    Update: A few people wrote in about spl_autoload(). I did not mention it here because it is only available since PHP 5.1 and thus is not widely available yet. However, if this is an option for you, it’s certainly worth considering.

  • Fluent Interfaces in PHP Dec 20, 2005

    Posted by Mike Naberezny in PHP

    Today on Martin Fowler’s bliki, I read a great new article describing what he calls “fluent interfaces“. Normally, most setter methods of an object will return void. In an object with a fluent interface, setters will instead return an object to promote object chaining.

    In PHP 4, it was not possible to do chaining, but one of the great new features of PHP 5 is that it supports directly deferencing objects returned by methods. It might sound complicated, but it’s really not and it has the potential to greatly improve the readability of some code. Let’s take a look at how to implement a fluent interface in PHP.

    Fowler’s Java code uses the example of building an order for a customer, which I’ll show here as the equivalent PHP 5 method:

    private function makeNormal(Customer $customer) {
        $o1 = new Order();
        $customer->addOrder($o1);
        $line1 = new OrderLine(6, Product::find("TAL"));
        $o1->addLine($line1);
        $line2 = new OrderLine(5, Product::find("HPK"));
        $o1->addLine($line2);
        $line3 = new OrderLine(3, Product::find("LGV"));
        $o1->addLine($line3);
        $line2->setSkippable(true);
        $o1->setRush(true);
    }
    

    The example above could definitely benefit from some whitespace and inline comments, but it’s still pretty unruly even with them. A possible solution to improve this code is to implement a fluent interface. Here’s the same code as above, expressed as a fluent interface:

    private function makeFluent(Customer $customer) {
        $customer->newOrder()
                 ->with(6, "TAL")
                 ->with(5, "HPK")->skippable()
                 ->with(3, "LGV")
                 ->priorityRush();
    }
    

    This is much more readable compared to the last example. Notice one thing unconventional about the example above: the lines do not terminate with semicolons. Since PHP is whitespace agnostic, it is the $same->as()->this().

    In PHP 5 terms, a fluent interface to an object is one where the setter methods return an object handle. It is perhaps simplest to always return $this, however any object handle can be returned. Here’s a simple PHP class that demonstrates how a fluent interface is built:

    class Fluent {
        public function hello() {
            echo "hello ";
            return $this;
        }
    
        public function world() {
            echo "world";
            return $this;
        }
    }
    
    $fluent = new Fluent();
    $fluent->hello()
           ->world();
    

    The code above will output hello world. As you can see, a fluent interface is quite easy to implement. Both Martin Fowler and Richard Davey recommend carefully considering where to use them. When done right, this technique has the potential to significantly improve the readability of some code.