Zend Framework titbits

January 18th, 2009 | Ekerete

There are a couple of Zend Framework snippets and how-tos I find myself googling over and over again. I have decided to maintain this list and keep adding to it as I go along.

  • Bypassing Zend_Db prepared statements:For complex queries, you may have to write the query out by hand and we recently had to do that. However Zend_Db insists on preparing ALL statements and a PDO bug forced the need to bypass this by accessing the connection object directly.
    To do that run:

    $result = $db->getConnection()->exec('SELECT * FROM users');

    More in the documentation

  • Disable Zend_Layout
    public function ajaxAction() {
    // disable layouts for this action:
    $this->_helper->layout->disableLayout();
    ...
    }
    
  • Disable Zend_ViewRenderer
    public function processingAction() {
    $this->_helper->layout->disableLayout();
    
    // disable the view for this action. e.g. actions that redirect after processing
    $this->_helper->viewRenderer->setNoRender();
    ...
    }
    

Restful authentication with Rails 2: Usage

January 18th, 2009 | Ekerete

This blog has been inactive for ages and one of my 2009 resolutions is to show the poor thing some love! I will try to keep it even if it’s the only resolution I don’t give up on. Things have become a bit less hectic at work (or maybe I’ve just gotten used to the system) and the spirit is willing so hopefully …

In my post detailing the installation of the Restful authentication plugin, it was pointed out to me in the comments that I didn’t show the actual usage of the plugin. My bad! This post will amend that oversight.

As an aside, while my tutorial post is still very relevant, I don’t do the installation from scratch anymore. In one of my earlier posts, I mentioned Bort and I still recommend it as a way of speeding up the initial setup of your rails project. However, the usage is the same whether you do the installation manually or use Bort.
Another Rails starter app I have used is leethal’s blank-rails-app. This is as light as they come and I use this when I do smaller sites in Rails rather than full fledged apps.

One of the advantages of installing manually is that Bort defaults to using RSpec as the test framework (at least on my system).
A manual installation checks for the presence of the spec folder and if it doesn’t exist, it creates the default Test::Unit tests.
However, Rails creates both a spec and test folder when i create a new Rails project (presumably because I’ve got the rspec gem installed ) and so to use Test::Unit I have to delete the spec folder before running the plugin’s generator.

To use the Restful Authentication plugin in your Rails app:

  • Include AuthenticatedSystem
    The generated controllers include the AuthenticatedSystem module but we need this available to all controllers.
    Delete the ‘include AuthenticatedSystem’ line from the Sessions and Users controllers and move the line to the application controller.
    The AuthenticatedSystem module (located in lib/authenticated_system.rb) contains the core methods used in our application code for authentication.
  • Add a before filter in the controllers you want to protect
    For any controller with actions that need protecting, add a before filter to the controller.

    class PageController < ApplicationController
    # protect all actions in this controller
    before_filter :login_required
    ...
    
    class PageController < ApplicationController
    # protect all actions in this controller except the index action
    before_filter :login_required, :except => :index
    ...
    
    class PageController < ApplicationController
    # protect all actions in this controller except the index and contact actions
    before_filter :login_required, :except => [:index, :contact]
    ...
    
    class PageController < ApplicationController
    # protect only the support action
    before_filter :login_required, :o nly => :support
    ...
    

    For the protected actions, the user is redirected to the new session url. We’ve already added a named route called ‘login’ to the routes.rb file pointing to this same action and I’d rather have my urls end with ‘/login’ than ‘/sessions/new’.
    To do that I override the access_denied method in the application_controller.rb.

    class ApplicationController < ActionController::Base
    helper :all # include all helpers, all the time
    
    include AuthenticatedSystem
    
    def access_denied
    alias new_session_path login_path
    super
    end
    ...
    
  • Use the plugin methods in your controller
    def index
    if logged_in?
    @profile = current_user.profile
    # or
    # @profile = Profile.find(current_user)
    end
    end
    
  • Use the plugin methods in your view
    
    <% if logged_in? %>
    Welcome <%= current_user.login %>
    Your Profile: <%= @profile.description %>
    <% end %>
    

And that’s all there is to it. Now get building!

Zend Framework – my three month review

November 6th, 2008 | Ekerete

I have been using the Zend Framework almost daily for the past three months and my verdict on it is a mixed bag. I really, really wanted to like ZF three months ago when we chose to use it at work for our ongoing project and I do – with a few reservations.

I know my verdict is tainted by Ruby on Rails and CodeIgniter (I’m proficient in the use of both of them) but it’s always nice to have a reference point. I’ll get my reservations out of the way first.

What I don’t like

  • Zend Framework Validation:
    The Zend Framework has a very robust and flexible validation library. However the framework encourages validating data in the controller. In my view, validation is business logic and is thus a model function. Our current implementation actually moves the validation to the model (we added smarts to Zend_Db_Table_Row and implemented an ActiveRecord).
  • Zend Forms:
    In the same vein, ZF encourages creating complete forms in the controller. A form is HTML and belongs in the view. Furthermore we have designers working with us and as such real forms are preferable. On my own personal projects though, I suppose creating my form (including validation) the Zend Way would actually speed up my work. The jury’s still out on that one, though.
  • Learning curve:
    ZF is complex. After three months I still haven’t covered all the fundamentals and constantly have the manual open. I guess this means it’s got a lot of functionality but it also means I’m still a ZF beginner.
  • Verbosity:
    ZF has a more verbose syntax than the other frameworks I’m used to.

    Compare the following view code:

    Zend Framework: <?php echo $this->escape($this->name); ?>;
    Ruby on Rails: <%= h(@name) %>

    And the following controller code:

    Zend Framework: $data = $this->getRequest()->getPost('name');
    CodeIgniter: $data = $this->input->post('name');
    
  • Flexibility:
    The Zend Framework is flexible (perhaps too flexible?). For everything that needs doing in ZF, there are at least three ways of doing it. This means it’s highly unlikely that two applications written with ZF will be similar unlike a rigid framework like Rails or CakePHP. Comparing the source for Magento Commerce and Digitalus CMS (two open source web apps built on the Zend Framework) proves this.

What I do like

  • Flexibility:
    Yes, the flexibility is both a minus and a plus for me. ZF can be twisted to do practically anything you need it to do.
    The classes can be easily extended and have loads of configurable options. With ZF, if you can think it, you really can do it.
  • The Education:
    Browsing the Zend Framework source code is a real education in best practice PHP programming and the use of design patterns in PHP. ZF is clearly written by folks who know their stuff and really highlights the best of PHP5 programming.
  • Proper Decoupling:
    The Zend Framework components honour the open/closed principle to the letter. The classes are so easy to extend and to reuse within and outside the framework. The ease with which modifications can be made actually encourage experimentation. A case in point is the ActiveRecord functionality we added to ZF. It’s a welcome change from all the intercoupling in CodeIgniter. I actually gave up trying to get CodeIgniter models to run isolated unit tests because the models needed an instance of the CI object to work.

  • Zend Test:
    ZF comes bundled with a built-in testing component based on PHPUnit (since version 1.6). Actually that was the clincher for me in the choice of framework as the Zend’s IDE (more on this below) comes bundled with PHPUnit testing support. The test component does have a couple of things lacking (in my opinion database support would have been nice) but it wasn’t hard to extend it to our liking. Also, I’m sure with later versions, this component will be improved. CakePHP does have a better-featured test framework based on simpletest but I do like the IDE support (with code coverage) in the ZF offering.
  • Zend Studio:
    Zend Studio rocks! Zend Studio has built-in support for the Zend Framework, PHPUnit testing, code coverage, debugging and loads of other goodies to speed up PHP work. If you code PHP for a living, you owe it to yourself to check this out. The support for ZF has also eased the learning curve considerably. I still fall back to Dreamweaver if I’ve got extensive CSS or HTML code to write but I’m slowly starting to use Zend Studio even for these although DW is still way better.

Would I use ZF for my own personal projects? It depends. I actually plan to use it for an application I will be realeasing next year but the motivation to use it is based on the modularity and the ease with which the framework can be extended and not development speed. For a more focused web app, I’ll still stick with CI.

Jump start your next Rails 2 application

October 29th, 2008 | Ekerete

Ruby on Rails has gotten really popular owing mostly to its well-earned reputation for rapid web application development. The plugin system has also helped to add loads of functionality not built into the core. It is almost certain you’ll find a plugin (or solution) to solve most problems you run into as long as it’s not too obscure.

However you can do better than typing ‘rails PROJECT’ to start a new rails app. I have used both bort and insoshi as bases for my new rails application and I recommend them highly.

Bort – A Base Rails Application

Bort is a base Rails application with various commonly used plugins pre-installed. Various maintenance tasks have also been done (e.g. the index.html file has been deleted, the views have been modified and the database has been set as the session store).

The package includes plugins I usually end up installing and saves me a couple of hours when I start a new Rails app. Pre-installed plugins include Restful Authentication, Exception Notifier, Will Paginate and Asset Packager. I actually use a fork which is essentially the same but uses usernames email addresses for authentication with the Restful Authentication plugin rather than email addresses usernames.

The downside when I started was the use of RSpec rather than Test::Unit but then it did force me to start using RSpec and I’m glad I did.

Insoshi – Social Networking Platform

For a social site, Insoshi will save a lot of time. It is an open source social networking platform built on Rails and it rocks! Apart from being a complete application you can build from, it’s also got loads of pre-installed plugins which include Will Paginate, Restful Authentication and Attachment-fu.

Like Bort, it uses RSpec rather than Test::Unit. Check it out.

Tips for the budding PHP developer

September 30th, 2008 | Ekerete

The ease of learning PHP and the trivial deployment of PHP applications (just upload and go) has resulted in everyone’s cousin coding with it and the accompanying impression of being a ‘toy’ language.

The following tips should help the aspiring PHP professional stand out from the crowd:

  • Step away from Dreamweaver
    To write PHP code efficiently, you need an IDE designed for PHP. If most of your work is with HTML and CSS, you won’t find a better editor than Dreamweaver but if you primarily write PHP code, a PHP editor with features like real time error detection, source control integration, code completion, refactoring support, debugging and built-in unit testing helps big time.
    After using Zend Studio for a while now, I am a convert and the version 6.1 is really awesome.
  • Get Certified
    Writing the PHP certification exam forces you to read up on stuff you my not have come across in your day to day programming. The increased your employability is also a very welcome side effect.
  • Use version control
    You can thank me later – specifically when your client calls you up at 9 o’clock in the evening to tell you he’s overwritten some of the files you uploaded to his server.
    Git is the current version control golden boy but I’ve found Subversion to be stable and effective. Online version control services (e.g. Springloops, Github, CVSDude and Beanstalk) have also reduced the barrier to entry and there’s now to excuse not to do source control.
  • Develop locally
    Repeat after me – ‘I will not edit code on the production server’. It is essential to have a webserver running on your development machine. All code can be tested rigorously before being deployed to the production server (from the source control repository, obviously). WampServer and Xampp for Windows and Mamp for the Mac take the stress off setting up a local web server. Use one of them.
    News Flash! – You don’t have to use Windows. Using a desktop Linux flavour (my choice is Ubuntu) gives you an environment as close as possible to your production server (assuming the PHP installation is on a Linux server – most are) and setting up webservers, virtual hosts and the like on these systems is also a lot easier (due partially to the massive amount of information on the internet).
  • Don’t just write it, learn it
    It’s amazing how much you can still learn even after working with PHP for years. Programming involves continuously updating your knowledge and skill-set and online resources and books should feature in your everyday work life. The PHP manual and Google are your friends.
  • Learn a web framework
    A web framework will speed up your code. Common plumbing tasks are already included and you just need to write code specific to your application. Choose one and learn it well.
    Which to choose? It depends. For the programmer just getting into OOP and frameworks, CodeIgniter is the easiest to learn but the rigidity of the CakePHP framework may also appeal. My personal preference is a combination of CodeIgniter and the Zend Framework.
  • Comment your code
    The guy who gets to maintain your code after you will find you and hit you over the head with a big stick if you don’t comment your code. Coming back to your code after a while, chances are you won’t understand what some of the code you wrote is supposed to do.
    That said, most of the comments I write adhere to the PHP Documentor standard and I try not to add comments within method blocks but rely on the doc blocks to show intent (thus avoiding the issue of stale comments – changing implementation code and ‘forgetting’ to change the comments). This also has the side effect of forcing me to keep my methods focused, which is good.
  • Test Drive your code
    You need to do unit testing. Test Driven Development gives you a safety harness when making changes to already working code and a criteria for certifying a piece of code as working.
    PHPUnit and SimpleTest are most commonly used for PHP unit testing.