In Defiance of Titles

Just another WordPress.com weblog

Posts Tagged ‘Zend Framework

Building a new blog

leave a comment »

Although I’ve loved using WordPress for the duration of this blog, recently I’ve been working on a custom replacement blog platform that I can host and maintain myself. This probably sounds odd, especially since there are already so many excellent blogging platforms available, but I’ve pushed ahead with it for a couple of reasons I think most developers will understand:

  1. Here at wordpress.com, I’d have to pay for certain features I can get for free with a self-hosted solution; I’d rather pay for hosting than pay for, say, custom templating.
  2. Although I could run WordPress or Drupal on a self-hosted domain, I still wouldn’t really be in control of the platform; a tailor-made solution will do exactly what I want it to, no more, no less.
  3. Most importantly: I blog primarily on my free time, mainly about projects I’m doing to hone skills I don’t typically get to use during my day job. I use Drupal all day at work, so using it for my blog wouldn’t really teach me anything.

The new platform is based on my favorite open source framework, Zend Framework, and makes heavy use of the Doctrine ORM library; I’ve been using Zend Framework for several years now, but Doctrine is new to me (and fantastic, by the way) …so I’m learning some very helpful new skills, and that makes me happy.

If you’d like to take a look at the new blog, it’s actually already live at jazzslider.org; I still haven’t worked out all the kinks, especially as far as IE compatibility is concerned, but I believe it’s a step in the right direction.

Check it out and let me know what you think!

Written by jazzslider

November 25, 2009 at 10:56 am

A Reusable Zend Framework Content Module

with 3 comments

As a sort of proof of concept for the ideas I discussed in my previous post, I’ve put together the first draft of what could become a very helpful reusable module. With this post, I’d like to introduce my new Zend Framework “content” module, which provides several abstract components for a reusable model layer, along with a concrete framework for building a variety of content types sharing a common database-based persistence layer. With some (OK, a lot of) refinements, a module like this could easily form the foundation of an extremely extensible Zend Framework-based content management system.

You can check out the current trunk by issuing the following svn command in your project’s modules directory:

svn checkout http://jazzslider.org/svn/zf-content/trunk content

Here’s a more detailed look at the features:

  • First off, it provides a reusable abstract model-and-mapper[1] system with sensible defaults for persisting those models in a MySQL database (other kinds of persistence layers are easily supported). Both pieces incorporate a plugin architecture similar to that used in Zend_Controller_Action, so that new functionality can be added to all models compositionally.
  • It also provides a concrete implementation of all this called Content_Model_Post; this model is essentially just your basic revision-controlled title-and-body content type. The nice thing about the post model is that it’s designed to be extended; if you need additional fields, you simply need to write a child class and a mapper plugin that describes how to find the extra data. (The design concept owes a lot to the Drupal CCK module, but without any of the administrative bells and whistles; this module is still very much a programmer’s toolkit.)
  • The view layer for the posts system comes with a few handy helpers and filters; the filters are mainly for implementing things like HTMLPurifier, Markdown, GeSHi syntax highlighting, etc. in the view layer when rendering your content. The idea is described in more detail in one of my previous posts, but the solution I’ve implemented here is much better. One caveat: the filters won’t work unless you’ve got the associated libraries installed somewhere in your include_path (as described in the INSTALL.txt file in the root of the project).

I’m releasing the current version of the source code under the GPL for now so that anyone who wants to can see how it works; that said, I wouldn’t say it’s ready for use in a high-profile production environment, owing to a couple of factors:

  • While the system does keep track of content authorship right out of the box, it would do a much better job of it if it knew how its parent application kept track of the current user. The only expectation it enforces is that when you assign an author to a post, it either has to be a Zend_Acl_Role_Interface object implementation or a string role ID that can be resolved to such an object at runtime (you can control this part of the process through a model plugin). Once I’ve written my reusable “users” module, things may work more predictably.
  • While we’re on the subject of related modules…one of my next projects is to develop a “comments” module that provides comments to all posts (and all dependent content types). For that matter, I’d also like to piece together something that allows for tag-based content classification. These will all be separate, optional modules, in keeping with the idea that people should be able to drop in what they want and leave the rest aside.
  • The process of designing a new dependent content type is still a little over-complicated; I’m going to try writing a tutorial soon, and when I do, I’d love some feedback on how to simplify the process.
  • The code is not yet unit tested; I wasn’t quite sure of the best way to bootstrap my unit tests now that Zend_Application is involved, and so far I haven’t found any definitive guides on the matter. I’ll be looking into that soon, and if what I discover is useful I’ll certainly make a post about it.

At any rate, please take a look and tell me what you think; remember, this mainly serves as a proof of concept for some of the stuff I’ve been talking about in previous posts…and once I’ve got the other helper modules put together, I think it’ll be a lot clearer what I’m aiming at. Anyway, thanks for reading!

Footnotes

  1. [Back] The data mapper logic in this module accomplishes some of the same purposes as the proposed Zend_Db_Mapper component, but is in no way intended (or suitable) to replace it. My goal here was mainly to demonstrate how such logic could be built out as a distributable, reusable plug-and-play module now that Zend_Application_Resource_Modules is out of the gate. I’m looking forward to future developments on Zend_Db_Mapper, and if it finds its way into the official framework you can bet I’ll be using it for projects like this.

Written by jazzslider

June 15, 2009 at 6:38 am

Posted in Computers

Tagged with , , , ,

Distributing Zend Framework Modules

with 8 comments

It’s been almost a month now since the release of Zend Framework 1.8, and although I was very excited about some of the new features, it’s taken me awhile to digest that excitement into something bloggable. As a result, I apologize if I’m a bit late to the party…but I’d like to take a moment nonetheless to discuss the implications of my favorite 1.8 feature: Zend_Application_Resource_Modules.

Zend Framework has provided what it calls a “conventional modular directory structure” for quite some time now: specifically, Zend Framework modules are supposed to “[allow] you to separate different MVC applications into self-contained units, and re-use them with different front controllers”. Unfortunately, up until 1.8, I have never found this to be entirely accurate. Based on module architectures I’d seen in full-stack content management systems, I’d always kind of hoped that installing a module would be as easy as this:

  1. Download the source code and copy it into your application’s modules directory.
  2. Hooray, it works now!

Now, this was true enough for modules that only provided a couple controllers and view scripts, but the second you introduced, say, controller plugins or models in the include_path, you’d have to modify your application-level bootstrap file, providing it with detailed knowledge of what the module provides. Because of this, the framework hasn’t really inspired a lot of distributable, reusable third-party modules; after all, the process for installing them would actually have looked something like this:

  1. Download the source code and copy it into your application’s modules directory.
  2. Adjust your application entry point (index.php) to include the module’s models folder in the include_path.
  3. Adjust your application-level bootstrap file to register the new modules directory with the front controller, if you haven’t configured it that way already.
  4. Adjust your application-level bootstrap file to register any plugins or plugin paths it might provide.
  5. Install any database schemas that might have come with the module.
  6. Hooray, it works now!

The problem here is that the parent application (and the person installing it) has to know all sorts of nitty-gritty details about how the module does its business. In my opinion, a truly “self-contained” module would be able to handle a lot of the above process all by itself, without any modifications to the parent application; otherwise, it’s not really self-contained, and not particularly easy to distribute to other developers.

Enter 1.8

However, as I mentioned earlier, this situation has changed dramatically in Zend Framework 1.8, due to a wonderful little component called Zend_Application_Resource_Modules. Among other things, it provides the following:

  • Modules can now provide their own bootstrapping logic; no more need to register module-provided plugins, paths, etc. in the application-wide bootstrap file.
  • Autoloading of common types of module-provided classes is now automatically set up for you; no more need to add modules to your include_path, or even to require_once your module class files before you use them.

See the benefit? All of the application-level configuration we used to have to do can now be encapsulated in a bootstrap process provided as a part of the module itself. This cuts the above workflow down to something like this:

  1. Download the source code and copy it into your application’s modules directory.
  2. Install any database schemas that might have come with the module.
  3. Hooray, it works now!

Suddenly, the prospect of downloading somebody else’s reusable module is a lot more appealing.

Some further issues

You’ll notice, however, that this still doesn’t quite match my first ideal workflow. Although Zend_Application_Resource_Modules provides a lot of assistance in getting your modules bootstrapped once they’re installed, it cannot yet provide much assistance with the installation process itself. As a result, if you’re trying to install a distributed module that involves database schemas, you’ll still have to install those by hand.

It’s also worth noting that Zend_Application_Resource_Modules does not yet provide a way to track and enforce module dependencies. For the most part this isn’t necessary; by the time everything is bootstrapped, all module-provided code is available through autoloading. However, there are a couple of situations in which it would be necessary:

  • If Module A needs to use a class provided by Module B during Module A’s own bootstrap, Module B must have been bootstrapped first…otherwise the autoloader for Module B’s classes won’t be ready yet.
  • If Module A provides a plugin that, for whatever reason, assumes that a plugin from Module B always fires before it, then Module B’s plugins need to be registered before Module A’s.

I’m working (in my copious spare time) on a distributable module of my own right now that could really benefit from both dependency tracking and database installation…but with how much better module architecture has already gotten in 1.8, I can only assume that future releases will be even more elegant. In the meantime, keep an eye out for my new module; I’d love the benefit of community review once it’s ready.

Written by jazzslider

May 21, 2009 at 7:43 pm

Design Choices for Zend_Auth_Adapter_Flexible

leave a comment »

Well, I’ve finally gone ahead and posted a Zend Framework component proposal: Zend_Auth_Adapter_Flexible. It’s the same idea I wrote up in my last post, but with a few key modifications; I thought I’d take a minute or two to discuss those modifications here.

First, the new proposal does not involve a user model; it pulls authentication credentials directly out of the strategy class’s Zend_Form instance. This change is mainly due to the framework’s lack of a formalized model layer…plus, it reduces the complexity of the idea, which is always a good thing.

Second (on a related note), the new component does not make any attempt to standardize what type of identity gets stored by Zend_Auth. Since authentication strategies will be written on an ad-hoc application-by-application basis, I figure that developers will want to take their own approach to this.

Third, the new proposal will hopefully take advantage of Zend_Navigation to automatically generate a list of links to available authentication strategies. I’m really not sure of how that would happen yet, since the plugin loader class doesn’t have any methods for retrieving all available class names—but if the community thinks it’s a good idea, there will likely be suggestions on how to take care of it.

I did keep the basic class name structure intact, which may or may not be a good thing. Zend_Auth_Strategy_Interface would require a new namespace under Zend_Auth, and I don’t know that I have a good justification for that. I do know that authentication strategies need to be distinguished from regular authentication adapters, since they do more things and have more dependencies.

So there you have it—my very first Zend Framework proposal. If you’re a Zend Framework developer and what I’ve described sounds interesting to you, please go take a look (and leave comments)!

Written by jazzslider

May 7, 2009 at 6:44 pm

Flexible User Authentication with Zend_Auth

with 3 comments

The Zend_Auth component of the Zend Framework can really help simplify the process of developing a custom authentication system for your next web application. The basic process is already very well-documented, so let’s try something a bit more complex.

For this example, we’re going to allow our users to authenticate in one of multiple ways: e.g., against a database table, against an LDAP server, or by OpenID [1]. Zend_Auth already provides the necessary authentication adapters, so what we’ll be concerned with here is how to implement all three systems without ending up in an FSUC situation.

As I see it, the controller layer ought to have very little awareness of the underlying authentication mechanisms. Here’s what such a controller might look like:

class AuthController extends Zend_Controller
{
  public function loginAction()
  {
    // one composite authentication adapter encapsulates
    // all the possible auth strategies, and provides appropriate
    // form instances for each
    $adapter = new My_Auth_Adapter_Multipath();
    $adapter->setStrategy($this->_getParam('via', null));
    $form = $adapter->getForm();
    $this->view->form = $form;

    // we'll also need an empty user object for this
    $user = new My_User(array());
    $adapter->setUser($user);

    // and then, if the user has submitted the form and it
    // passes simple validation, go ahead and try to authenticate
    if ($adapter->shouldAuthenticate($this->getRequest(), 
                                     $this->getResponse()) 
     && $form->isValid($this->_getAllParams())) {
      $user->populate($form->getValues());

      $auth = Zend_Auth::getInstance();
      $this->view->authResult = $auth->authenticate($adapter);
      $this->render('result');
    }
  }
}

Looks pretty clean to me. The view script is even cleaner:

<h1><?= $this->translate('Log in') ?></h1>
<?= $this->form ?>
<h2><?= $this->translate('Other ways to log in') ?></h2>
<ul>
  <li><a href="<?= $this->url(array('via' => 'email')) ?>"><?= $this->translate('Email') ?></a></li>
  <li><a href="<?= $this->url(array('via' => 'euid')) ?>"><?= $this->translate('EUID') ?></a></li>
  <li><a href="<?= $this->url(array('via' => 'openid')) ?>"><?= $this->translate('OpenID') ?></a></li>
</ul>

The real magic is all happening behind the scenes in the model layer. Let’s take a look at the authentication adapter next:

class My_Auth_Adapter_Multipath implements Zend_Auth_Adapter_Interface
{
  protected $_strategies;

  protected $_user;
  protected $_strategy;
  protected $_request;
  protected $_response;

  public function __construct()
  {
    $this->_strategies = new Zend_Loader_PluginLoader(array(
      'My_Auth_Strategy' => 'My/Auth/Strategy/',
    ));
  }

  public function shouldAuthenticate(Zend_Controller_Request_Http $request, 
                                     Zend_Controller_Response_Http $response)
  {
    if (null === $this->_strategy) {
      throw new Zend_Auth_Adapter_Exception('cannot determine; must set strategy first');
    }
    $this->setRequest($request);
    $this->setResponse($response);
    return $this->_strategy->shouldAuthenticate();
  }

  public function authenticate()
  {
    if (null === $this->_user || null === $this->_strategy) {
      throw new Zend_Auth_Adapter_Exception('must provide both user and strategy');
    }
    return $this->_strategy->authenticate();
  }

  public function getForm()
  {
    if (null === $this->_strategy) {
      throw new Zend_Auth_Adapter_Exception('must provide strategy first');
    }
    return $this->_strategy->getForm();
  }

  public function getUser()
  {
    return $this->_user;
  }

  public function setUser(My_User $user)
  {
    $this->_user = $user;
    return $this;
  }

  public function getStrategy()
  {
    return $this->_strategy;
  }

  public function setStrategy($strategy)
  {
    if (!($strategy instanceof My_Auth_Strategy_Interface)) {
      $strategyClass = $this->_strategies->load(ucfirst($strategy));
      $strategy = new $strategyClass();
      $strategy->setAdapter($this);
    }
    $this->_strategy = $strategy;
    return $this;
  }

  public function getRequest()
  {
    return $this->_request;
  }

  public function setRequest(Zend_Controller_Request_Http $request)
  {
    $this->_request = $request;
    return $this;
  }

  public function getResponse()
  {
    return $this->_response;
  }

  public function setResponse(Zend_Controller_Response_Http $response)
  {
    $this->_response = $response;
    return $this;
  }
}

A few things worth noting here. First…usually in this type of workflow the controller would check $this->getRequest()->isPost() prior to firing the authentication method; however, certain authentication strategies may require authentication to fire on other conditions (for instance, the OpenID adapter should fire when the openid_mode parameter is set, regardless of the request method). So, we leave it up to the adapter’s shouldAuthenticate() method to determine if the request warrants authentication.

Second, note that we still don’t have much in the manner of authentication code; that’s because, in order to keep things as flexible as possible, we’ve offloaded the actual authentication work to an arbitrary collection of strategy classes [2], provided dynamically through a Zend_Loader_PluginLoader instance (to make this worth it, we’ll also eventually want to add methods for registering new plugin paths, but I’ve left that out for the sake of brevity). Each strategy class will need to conform to the following interface:

interface My_Auth_Strategy_Interface extends Zend_Auth_Adapter_Interface
{
  public function setAdapter(My_Auth_Adapter_Multipath $adapter);
  public function getForm();
  public function shouldAuthenticate();
}

Internally, each authentication strategy will simply configure one of the core Zend_Auth adapters, run its authentication method, and, if successful, ensure that the identity returned in the Zend_Auth_Result instance is the completely-loaded user object. Let’s take a look at the simplest of the three examples, which checks the user’s email address and password against a backend database table:

class My_Auth_Strategy_Email implements My_Auth_Strategy_Interface
{
  protected $_adapter;

  public function setAdapter(My_Auth_Adapter_Multipath $adapter)
  {
    $this->_adapter = $adapter;
    return $this;
  }

  public function getForm()
  {
    $form = new Zend_Form();
    $form->addElement('text', 'email');
    $form->email->setLabel('Email address')
                ->setRequired(true)
                ->setFilters(array('StringTrim'))
                ->setValidators(array(
                  array('EmailAddress'),
                ));
    $form->addElement('password', 'pword');
    $form->pword->setLabel('Password')
                ->setRequired(true);
    $form->addElement('submit', 'submitBtn');
    $form->submitBtn->setLabel('Submit');
    return $form;
  }

  public function shouldAuthenticate()
  {
    return $this->_adapter->getRequest()->isPost();
  }

  public function authenticate()
  {
    $user = $this->_adapter->getUser();
    if (null === $user->email || null === $user->pword) {
      throw new Zend_Auth_Adapter_Exception('must provide email and password');
    }

    // use an internal Zend_Auth_Adapter_DbTable instance
    // to do the actual authentication
    $internalAdapter = new Zend_Auth_Adapter_DbTable(
      Zend_Registry::get('dbAdapter'),
      'users',
      'email',
      'pword'
    );
    $internalAdapter->setIdentity($user->email)
                    ->setCredential($user->pword);

    $result = $internalAdapter->authenticate();
    // per the stated requirements, we also want to make
    // sure that Zend_Auth stores a fully-completed user
    // object as the user's identity; so, we'll populate the
    // user object from the retrieved row and then set up
    // a new result object containing the correct identity
    if ($result->isValid()) {
      $user->populate($internalAdapter->getResultRowObject());
    }
    $result = new Zend_Auth_Result($result->getCode(), $user, $result->getMessages());
    return $result;
  }
}

We’ll use the same principle in designing the remaining two authentication methods (LDAP, which our users will know as their “EUID” or “Enterprise User ID”, and OpenID). I’ve left getForm() and setAdapter() out of these next examples, because the basic technique won’t be much different.

class My_Auth_Strategy_Euid implements My_Auth_Strategy_Interface
{
  // ...

  public function shouldAuthenticate()
  {
    return $this->_adapter->getRequest()->isPost();
  }

  public function authenticate()
  {
    $user = $this->_adapter->getUser();
    if (null === $user->euid || null === $user->euidPword) {
      throw new Zend_Auth_Adapter_Exception('must provide EUID and EUID password');
    }

    $ldapOptions = $this->_getLdapOptions();
    $internalAdapter = new Zend_Auth_Adapter_Ldap($ldapOptions, 
                                                  $user->euid, 
                                                  $user->euidPword);
    $result = $internalAdapter->authenticate();
    if ($result->isValid()) {
      // again, we'll need to populate the user object from the
      // database here, only this time we'll need to actually load
      // the user in manually since LDAP is a different system
      $table = new My_Db_Table_Users();
      $select = $table->select()->where('euid = ?', $user->euid);
      $userRow = $table->fetchRow($select);
      if (null === $userRow) {
        // the user has a valid LDAP account, but doesn't have an
        // account on our site yet, so we'll need to create one
        // programmatically...I won't demonstrate this here, though
      }
      $user->populate($userRow);
    }
    $result = new Zend_Auth_Result($result->getCode(), $user, $result->getMessages());
    return $result;
  }

  // ...
}

And finally, a strategy class for OpenID. Note that this is a bit more difficult owing to the necessity of client redirects; the OpenID strategy needs to be aware of quite a few more details, most of which are stored in the request object injected from the controller during the shouldAuthenticate() method.

class My_Auth_Strategy_Openid implements My_Auth_Strategy_Interface
{
  // ...

  public function shouldAuthenticate()
  {
    $request = $this->_adapter->getRequest();
    if ($request->isPost() 
     && $request->getParam('openid_action', null) == 'login' 
     && null !== $request->getParam('openid_identifier', null)) {
      return true;
    }
    if (null !== $request->getParam('openid_mode', null)) {
      return true;
    }
    return false;
  }

  public function authenticate()
  {
    $user = $this->_adapter->getUser();
    if (null === $user->openid_identifier) {
      throw new Zend_Auth_Adapter_Exception('must provide openid');
    }

    $storageDir = APPLICATION_PATH . '/../temp/openid_storage';
    $storage = new Zend_OpenId_Consumer_Storage_File($storageDir);

    $internalAdapter = new Zend_Auth_Adapter_OpenId(
      $user->openid_identifier,
      $storage,
      null,
      null,
      null,
      $this->_adapter->getResponse()
    );

    $result = $internalAdapter->authenticate();
    if ($result->isValid()) {
      // again, load the user from the database and populate
      // the user object; note that if the user doesn't yet have
      // an account on our site, the above code would be very
      // easy to modify such that it uses the OpenID simple
      // registration extension to create the user automatically
    }
    $result = new Zend_Auth_Result($result->getCode(), $user, $result->getMessages());
    return $result;
  }
}

The end result of all this is an extremely flexible (and extremely extensible) user authentication system with very little business logic in the controller.

Footnotes

  1. [Back] The idea is similar, but not identical, to the Zend_Auth_Adapter_Chain proposal from January 2008; the main difference here is that instead of authenticating against a series of several adapters, we’re simply going to have one main adapter that orchestrates the whole procedure via easily-selected strategies. Only one authentication technique will ultimately fire.
  2. [Back] If you look at the code later on, you’ll see that my authentication “strategy” interface is just an extension of Zend_Auth_Adapter_Interface allowing each implementation to provide a few extra standard features (forms, request analysis, etc.). I suppose it would have been reasonable to simply call them adapters, but I decided on using a new (still fairly standard) name to make it clear that they’re doing more than the standard Zend_Auth adapter would do. It was also necessary to namespace these classes separately from any other Zend_Auth adapters that might be included in a given application, so that the plugin loader never accidentally loads a different implementation of Zend_Auth_Adapter_Interface.

Written by jazzslider

April 9, 2009 at 6:52 am

Output Transformation in a Zend Framework Model Layer

with 4 comments

A few weeks back, Matthew Weier-O’Phinney wrote a very helpful discussion of model layer infrastructure using various components of the Zend Framework. I especially appreciated his advice on using Zend_Form as an input filter inside the model class itself; it provides a very clean way to keep validation and filtering logic properly encapsulated.

Zend_Form’s use of Zend_Filter and Zend_Validate also makes it very easy to get precisely the filtering and validation rules you need. You can even filter through an external library like HTMLPurifier if you find you need the extra functionality, just by writing a new filter class; this has already been covered quite well (for example, see Part 8, Step 3 of Pádraic Brady’s Zend Framework blog tutorial). As Weier-O’Phinney demonstrates, you can then use this Zend_Form object as a screening filter in your model class, so that certain properties must always pass through the form’s validation process before they are set in the model itself. I won’t duplicate his logic here either, but you should definitely take a look at it.

However, I’ve run into a minor problem, and I’m not sure my solution is particularly ideal. See, the Zend_Form approach described above does a great job of implementing Chris Shiflett’s Filter Input, Escape Output principle…user input is filtered for invalid HTML before it’s ever saved to the model, and can then be escaped as appropriate in the view layer. But what happens if you need to be able to retrieve the user’s original unfiltered input later?

That might not sound like an appropriate thing to do, but consider this. Suppose that instead of simply sanitizing user-contributed HTML, you wanted to allow your users to use a simpler text input format (such as Markdown) and generate the HTML for them later? It wouldn’t be appropriate to save the generated HTML to the model, since your users would then be unable to retrieve their original Markdown version for later editing. However, if you don’t pre-generate the HTML, then you can’t perform your HTMLPurifier sanitizing at the input stage either, since there isn’t any HTML to sanitize yet.

In this situation, it looks to me like you’d be stuck doing all your input filtering in the presentation (output) layer, which doesn’t really dovetail well with Shiflett’s principle. But then again, there do appear to be two distinct types of “filtering” at work here, one of which is what Shiflett was talking about, and the other of which probably isn’t:

  1. Sanitization, or making sure that user input doesn’t contain any security risks.
  2. Transformation, or converting user input for presentational purposes. (I feel like this is different from escaping, since escaping is mainly concerned with defusing special characters?)

So what do you think? It’s clear that sanitization ought to be done immediately upon input (preferably in the form object), but where should transformation happen?

Rob Allen’s Zend Framework Overview from last year hints at implementing things like Markdown formatting in the view layer through the use of view helpers. This is certainly appropriate from a strict MVC perspective, as output transformation is definitely presentation-layer stuff. However, this isn’t particularly DRY; every time you wrote a view script utilizing this data, you’d need to remember to run it through the appropriate chain of output filters.

So, my best overall idea (building on Weier-O’Phinney’s examples) is to implement it in the getters in my model:

class My_Model
{
  // ...
  public function __get($property)
  {
    $method = 'get' . ucwords($property);
    if (method_exists($this, $method)) {
      return $this->$method();
    }
    if (array_key_exists($property, $this->_data)) {
      return $this->_data[$property];
    }
    return null;
  }

  public function getBody($applyOutputFilter = true)
  {
    $body = $this->_data['body'];
    if ($applyOutputFilter) {
      $body = $this->getOutputFilter()->filter($body);
    }
    return $body;
  }

  public function getOutputFilter()
  {
    $filterChain = new Zend_Filter();
    // add specific filter objects as appropriate, and then...
    return $filterChain;
  }
  // ...
}

This guarantees that whenever the “body” is accessed as a property, it’s correctly transformed for HTML output (a sensible default).

However, both of these approaches still leave us with the same core problem: you almost inevitably end up doing all your input filtering at the presentation stage, rather than prior to saving it to the persistence layer as is usually recommended. This can be a security risk if you’re not careful, and is almost certainly a performance hit for the average visiting user.

Any ideas on how best to resolve these issues?

Written by jazzslider

April 6, 2009 at 7:11 am