Dealing with dates… reporting, etc.

Once in a while I run into a situation, where some sort of reporting is required for an application…
(It happens.)

An example?.. We need to get a list of all active users in the DB.

Obviously CakePHP makes it overly easy for us.
However, it also happens, that once in a while we need to filter the list by using a “from” and “to” date range.

I really wanted to keep things simple and re-usable (yeah, lazy) and one solution came to mind…

It fits nicely within an MVC concept, and since I’ve got nothing else to write about, perhaps it might be worth sharing.

To get things started, we’ll consider a view:

  echo $form->create('User', array('action' => 'report_to_me'));
  echo $form->input('active_from');
  echo $form->input('active_to');
  echo $form->end('Set date');

<?php if(!empty($allActiveUsers)) : ?>
  <?php foreach($allActiveUsers as $user) : ?>
      <?php echo $user&#91;'User'&#93;&#91;'name'&#93;; ?>
  <?php endforeach; ?>
<?php else : ?>

    Ain't got no active users.
<?php endif; ?>

Pretty straight-forward… We display a user’s name for all active users from the DB.
Also, there is a way for someone to input a date range and send it off to the controller.

Let’s take a look at the action in the controller:

public function report_to_me() {
      if(!empty($this->data)) {
        $this->User->fromDate = $this->data['User']['active_from'];
        $this->User->toDate = $this->data['User']['active_to'];
      $this->set('allActiveUsers', $this->User->getActive());

If no date is supplied (i.e. $this->data is empty) we show all active users from the DB.
Yet, if the date is supplied we set a few properties in our User model…
You might notice that I like fat models (eh?), therefore the goal is, once again, to avoid any logic in the controller.

With that being said, we’ll take a look at the User model:

    class User extends AppModel {
      public $fromDate = NULL;
      public $toDate = NULL;
      public function getActive() {
        return $this->find('all', array('conditions' => array('User.is_active' => 1,
                                 'recursive' => -1));
      private function getDateConditions() {
        if(!empty($this->fromDate) && !empty($this->toDate)) {
          return array($this->alias . '.' . 'created BETWEEN ? AND ?' => 
                 array(date('Y-m-d', strtotime($this->fromDate)), 
                       date('Y-m-d', strtotime($this->toDate))));
        return FALSE;

The only interesting piece of code here is the getDateConditions() method.
Once we set the $fromDate and $toDate properties, the method gives us a nicely formatted condition for the date range. Otherwise, as promised, we get a list of all active users (no date condition is applied).

Observer Pattern the CakePHP way

First, I’d like to thank the original author of this article for giving me inspiration, food for thought and a solid code base to further dwell on this idea.

So what is the Observer Pattern anyway, and why is it a good thing to implement?

Many resources will tell you that the Observer Pattern is based on the two main concepts: The Subject or the the object being watched and the Observer, the object that is doing the observation. Let’s see if we can take a closer look in more practical terms.
Imagine that we have a User model (The Subject), you can save the User, edit the User, search the User, delete the User. All of these events can be observed and in general we can say that whenever one such event takes place, it means that the User state has changed in some way.

Now, let’s say whenever such state change takes place other parts of our system should perform a certain action, for example when a new User is saved an email should go out.

Of course you’d say that this is pretty easily done in the controller, for example:

if($this->User->save($this->data)) {

We’ve seen this many, many times before. However there is a problem with such implementation. First of all we are adding unnecessary logic to our controller, secondly if we need to perform other actions, besides sending an email, but in fact notify twenty other parts of the system (such as maybe logging some info, moving the User into a guest group, setting up an LDAP account, registering him/her at some remote web site… blah… blah) you’ll see how quickly the code can grow and if the necessary logic isn’t neatly tucked away it will become a serious nightmare to maintain.

Therefore one of the most important benefits of the Observer Pattern is decoupling between various parts of the system.

Let’s continue with this example…

The User object is saved, but now we have an Observer watching/listening for certain events. As soon as it sees that the new User was saved the observer kicks-in and begins to do its job. The great news is that the User object doesn’t care about anything beyond saving the user data, it is the Observer’s responsibility to handle additional tasks as deemed necessary.
Another good bit of news is that the User object can (and probably will) have multiple Observers watching for its every action, each one can then take care of the tasks it was meant to do (i.e. sending out an email, logging, creating account, doing registration, buying flowers). Each one of these tasks can be handled (if desired) by a separate observer.

Again we are ensuring reduced coupling and improving our system’s flexibility and maintainability along the way… and as your application tends to grow, these are very good things.

Now, that we’ve established some ideas about the Observer Pattern, let’s take a look at the CakePHP implementation (again largely based on the article by Chris Lewis).

Our models are going to become Observable by using the Observable Behavior and our Observers will be registered as components of various controllers.

Since the behavior implements all of the callback methods of the model, our Observer will be able to handle any event associated with the model i.e.:


The behavior and the component are at the end of article. Please note, that the component code is a skeleton one, i.e. it doesn’t implement any specific functionality, because whatever your observer needs to implement is highly depended on your specific application. However it should give you a solid foundation to build many various observers.
Eventually I will move the code to GitHub so that some common functionality that might be applicable to many applications can be further added and expanded.

So how would you use something like this?
Following our example, first, attach the behavior to the User Model.
Secondly, add the Observer component to your relevant i.e. Users Controller.

And really that’s all there is to it, you’ll notice a bunch of methods in the component that look quite similar to the model callbacks. For example if you wanted to send out an email after the User is saved, you’ll place the appropriate code inside the modelAfterSaving() method of the Observer component… and so on, and so forth for any and each of the other implemented methods.

Also, you can use the sekeleton component to easily build your own to handle any specific task that you might require of your observer. Remember that you can (and should) have multiple observers based on their own responsibilities.

Well, that’s about it folks. I hope you’ll find these little code snippets useful and get inspired to use such an approach to make your application even more flexible and well-oiled.

P.S. If you have questions or would like more concrete examples, please don’t hesitate to ask, and I’ll be glad to do a follow up.

The Behavior:

class ObservableBehavior extends ModelBehavior {
    public $observers = array();
    public $implementableMethods = array('beforeSave'   => 'modelBeforeSaving',
                                         'afterSave'    => 'modelAfterSaving',
                                         'beforeFind'   => 'modelBeforeFinding',
                                         'afterFind'    => 'modelAfterFinding',
                                         'beforeDelete' => 'modelBeforeDeleting',
                                         'afterDelete'  => 'modelAfterDeleting');
    public function setup(&$Model, $settings) {
      if (!isset($this->settings[$Model->alias])) {
          $this->settings[$Model->alias] = array();
      $this->settings[$Model->alias] = array_merge($this->settings[$Model->alias], (array) $settings); 
    public function addObserver(&$Model, $observer) {
      $args = func_get_args(2); 
      $observer = $args[2];
      array_push($this->observers, $observer);      
    public function beforeFind() {
      return $this->notifyObservers();
    public function beforeSave() {
      return $this->notifyObservers();
    public function afterFind() {
      return $this->notifyObservers();
    public function afterSave() {
      return $this->notifyObservers();
    public function beforeDelete() {
      return $this->notifyObservers();  
    public function afterDelete() {
      return $this->notifyObservers();  
    private function notifyObservers() {
      $backtrace = debug_backtrace();
      $callingFunction = $backtrace[1]['function'];
      $valid = TRUE; 
      foreach($this->observers as $observer) {               
        $valid = $valid && $observer->{$this->implementableMethods[$callingFunction]}();    
      return $valid; 

The component:

class ObserverComponent extends Object {
    public function startup(&$controller) {                
        $this->controller =& $controller;
        $this->Model =& $controller->{$controller->modelClass};               
        $this->Model->addObserver($this->Model, $this);
    public function modelBeforeFinding() {        
      echo '<p>beforeFind</p>';
      return TRUE;
    public function modelAfterFinding() {
      echo '<p>afterFind</p>';
      return TRUE;
    public function modelBeforeSaving() {
      echo '<p>beforeSave</p>';
      return TRUE;
    public function modelAfterSaving() {
      echo '<p>afterSave</p>';
      return TRUE;
    public function modelBeforeDeleting() {
      echo '<p>beforeDelete</p>';
      return TRUE;
    public function modelAfterDeleting() {
      echo '<p>afterDelete</p>';
      return FALSE;

Save now, sanitize later…

Good discussion came up on IRC today, regarding sanitizing of the data.

I’d like to clear up a little confusion and hopefully set the record straight on the sanitizing of data.

First, we need to keep in mind that there are two types of “evil” data, which most web developers are worried about.
One can hurt your database and the other one that can hurt your HTML pages.

Therefore, it is generally advisable to protect your web application against:

1. SQL Injection
2. XSS, or cross-site scripting.

It is, however, important not to mix up the two and realize at which point it is appropriate to protect yourself (or your app) from harm.

First, the good news. With CakePHP you are automatically protected from SQL injection IF you use CakePHP’s ORM methods (such as find() and save()) and proper array notation as outlined in the manual. The bad news is that if you are playing around with plain SQL or do not adhere to proper CakePHP syntax of writing queries, you could still be vulnerable to an SQL injection attack.

To be a little more specific, CakePHP will quote and escape all fields and values in your queries, assuming you’re following the rules, to keep your DB nice and safe.
(If you care about more details, see here).
It is important to note, that updateAll() does not escape the fields, so be cautious when using it.

So, technically you have to worry very little about SQL injection when working with CakePHP.

Now, what about user inputting some evil scripts into your blog to hijack your site?

I think the most important point here is that any HTML script, tag or trick is perfectly safe to store in your database as is.
The basic rule is that you do not need to sanitize HTML data in any way before saving it into the database.

When you are concerned about XSS it is the output of data from the database that you need to worry about. If you display raw data from the DB, it is quite possible that you’ll have “evil scripts” injected into your page. With CakePHP it is easy to combat enough with a handy h() method.

Are there cases where you must sanitize HTML before saving it to the database?
Probably, but I can’t really think of any.
Even if your application requires it, you might want to create two fields in the relevant table raw_data and sanitized_data, as an example.

P.S. AD7six just proposed an excellent question, which he also answered just as well… Why allow script code to be stored in some user’s profile? The answer is that having this raw (although unwanted) data is useful for tracking and dealing with malicious users. That’s where having two fields in the table to store sanitized and raw data might come in very handy. If you remove the script tags prior to storing the user information, it’ll become much harder to find and flag users who are obviously trying to screw with your app.