Internet Strategy Guide

Together we can defeat the internet

Tuesday, June 30, 2009

headers exception with Zend_Session while unit testing

While the manual for Zend_Session does discuss unit testing and the read-only exception, it has no mention of an exception I encountered recently while unit testing. I admit that the reason I encountered the exception is most likely because I'm Doing It Wrong. However, given reality, I did not have time to properly make the class, or at least do it better. I received the following exception:

exception 'Zend_Session_Exception' with message 'Session must be started before any output has been sent to the browser; output started...'

The problem was, of course, that the feedback from previous tests was already outputted to the screen. I could've solved this by playing with my test suite and just starting sessions at that level but that wouldn't have been the best solution. In fact, I'd qualify that solution under bandaids (solutions that mask a problem instead of fixing them). If you can't see why it is a bandaid, I'm happy to discuss it but for once, I"m going to try to stay on topic and not digress any further than I have.

So, here's the scenario:

  • not enough time to refactor the class so that sessions are only called/created when necessary
  • sessions are being called because we're testing some auth stuff which relies on session information, we might not be able to do DI (see above)
  • we want to minimize contributing factors to test failure so session has to be called/destroyed for the tests that need it, all other tests should never have session existing

The solution? A little 'undocumented' static variable:

Zend_Session::$_unitTestEnabled = true;

Ok, undocumented is a bit misleading. You won't find out about it by looking at the Manual but will find it when you're digging through the API. So it is documented, just not well. I'm guessing because it is rare to encounter the exception. I'm not surprised that I encountered it since my projects always seem to have some degree of weirdness, which makes for an interesting learning curve thats compounded with Zend's curve.

posted by chance at 6:57 am  

Tuesday, February 24, 2009

zend_log_exception ‘bad log priority’

I'm writing this post because there are a few times I've gotten this particular exception and then look at the trace and can't figure out what's wrong. More often than not, I'll get to the line in the trace and be like, "wtf! there's no priority here. It's a method call not a constant". This turns into, let's see if something is happening before this method is called and finally comes down to looking at the Zend_Log source and remember, "oh yeah, Zend_Log allows you to use log by priority name as a method in lieu of using the log method" and what I once thought of as slick when I read the documentation turns into a waste of a few minutes and added amount of aggrevation. So to save myself and others some time and aggrevation, I'm going to go into a bit of detail as to why you may be getting this exception.

Take the following for example:

// assume taht $log is a valid instance of Zend_Log
$log->addEventItem('foo','bar');

It looks like it should work, right? It won't because the correct method call would be

$log->setEventItem('foo','bar');

As I explained in the introduction, the 'bad log priority' exception will be thrown for this sort of error. This error will occur because Zend_Log overloads the __call function so that you can do

$log->priorityName('message');
// instead of logging with the log method
$log->log('message',Zend_Log::PRIORITY_NAME);

So if you're like me and get this exception but only see a method where this error is being thrown, you now know why and hopefully be less confused and aggrevated.

I wish I could provide a solution to this issue but I see no way that Zend_Log can contextually tell if you're wanting to use the priorityName shortcut or not. This only leaves the option of removing the the priorityName shortcut entirely, which will break somebody's code. The shortcut is nice because of its flexibility but definitely a case where flexibility can increase complexity or rather, flexibility leading into complications that require complex understanding. I haven't had time to read all the arguments in the comments on the flexibility/complexity issue that Federico Cargnelutti brought up recently to have an overall opinion on the matter but in regards to Zend_Log, the flexibility should've been left out. I would've preferred that Zend kept it simple and just made log the only method of logging. Or maybe I'm an edge case that logs more information than the initial event items give me.

posted by chance at 10:43 am  

Wednesday, December 17, 2008

Zend_Log quickstart

Lately, I've found that I need to create a more robust logging system for both audits and debugging. I found a great logging primer from DevShed that offers some good insight into going about making a more robust system. Other than the theory, you shouldn't really take much more away from it since, as one comment points out, the implementation is poor aka globals are bad. Caveat: my implementation probably won't be all that great either but I hope to avoid making beginner's mistakes.

That being said, the reason this particular article is centered on Zend is because I'm pretty much in love with Zend right now. The main reason for writing this article is that, while the Zend documentation on Zend_Log is thorough and easy to understand when you read it, I hate back and forth between the sections of Zend_Log to make sure I understand what I'm needing to do.

I'm assuming you have at least gone through the Zend Quickstart before reading on. For my filesystem and db configuration, I use Zend_Config to load up settings such as the logfile name and log database adapter. I could've set the path for the file but I want a certain degree of flexibility.

At this point, I have the logger configuration from zend config  and the db adapter so let's move on to some code examples. This is partially taken from my in-progress class.

making a full filepath:

$filepath=(isset($options['FilePath'])) ? $options['FilePath'] : INC_PATH."/".$this->_systemConfig->system->logfile;
$writer = new Zend_Log_Writer_Stream($filepath);

the filepath is used with the Zend_Log_Writer. Next we set a format for the writer and then instantiate Zend_Log with the writer

$formatter=new Zend_Log_Formatter_Simple($format);
// specify format
$writer->setFormatter($formatter);
$logger=new Zend_Log($writer);

Note: $format is a text string that indicates how each log entry will appear.

The important things to remember here is that Zend_Log creates an associative array with all the basic useful log information. This array can be accessed in a variety of ways. For my purposes, knowing what is accessible by the stream and database writers are important.
If you have read the documentation thoroughly, you will have found that in section 30.1.6 Zend documents this array expressly. Unfortunately, unlike some most of their other documentation, this useful bit of information is almost secreted away. I've scoured the docs a lot to find the keys created by Log so here they are as a quick reference.

  • timestamp
  • message
  • priority
  • priorityName

These little gems are pretty much the keys to the Kingdom of Zend_Log.
If you want to reference them for formatting in a stream, you can do something like:

$format = (isset($options['LogFormat'])) ? $options['LogFormat'] : '%timestamp% '
.PHP_EOL.'%priorityName% (%priority%)'
.PHP_EOL.'%message%' . PHP_EOL.PHP_EOL
.str_repeat("=",100). PHP_EOL;

or if you need to use them for your db, you can use set column mapping like so:

$columnMapping = array('lvl' => 'priority','Priority'=>'priorityName', 'msg' => 'message');
$writer = new Zend_Log_Writer_Db($db, 'log_table_name', $columnMapping);

That should cover the basics.

Pro-tip discussion: For auditing, you may want to make separate log files for access,create,and changes made to your app/system. Error logging should log everything into files, but a separate debug copy would probably out in the development environment. I usually do a tail -f on debug/log file. It seems obvious to, me that any logging/exception system you make should have a simple outside error handling function to alert you of that logging broke. I believe this can be done by setting the error handler in the constructor. Haven't played with this yet. It seems to me that any robust logging system you implement will run into a chicken vs the egg type problem

posted by chance at 10:54 am  

Tuesday, October 21, 2008

understanding zend ini (Zend_Config_Ini)

So I just spent the past half hour reading and sorting through documentation on Zend_Db, Zend_Config and Zend_Config_Ini so that I could set my driver options in my config file.

I could've set the options in the bootstrap but figured there had to be a way to set things up in my ini file. After all, what would the point of an ini file be if you can't set your configuration options in them?

The key to my issue ended up being Zend_Db. The bootstrap (if you followed the quickstart like i did) uses Zend_Db::factory() to set up your database connection. It does this by loading the configuration ini that you made. What the quickstart fails to mention is how to decipher your ini file. Or maybe it's some kind of Zend right of passage to figure out how to go beyond setting up your environemnt host/dbname/username/password. Or maybe I'm just incredibly dumb. I'm more prone to believing the latter.

So for the sake of anyone else like me that possesses the curiousity to know why things work the way they do but don't possess the patience to root documentation while doing a quickstart, here is a brief "wft is going on here".


Zend_Db::factory($configuration->database);

gives us a database adapter. It does this by parsing a Zend_Config object. If you're using an ini, then Zend_Config_Ini parses your ini file by replacing creating arrays by (to extremely simplify) exploding the dots (.). So

database.adapter=PDO_MySQL
database.params.host=localhost
database.params.dbname=kittens

becomes equivalent to

$database=array(
  "adapter"=>"PDO_MySQL",
  "params"=>array(
         "host"=>"localhost",
         "dbname"=>"kittens"
          )
    )

Sidenote: I found that if you have a password that contains non-alphanumeric values, it's best to encapsulate them in double-quotes. (i.e. database.params.password="kittens!") otherwise it cause Zend to hate you (short version of the outcome).
This basic understanding on how the ini file is parsed lead me to being able to do all sorts of fun stuff. In particular, was setting the driver options.
At first I thought I could do something like database.driver_options or database.driver.options to set things up. It made sense to me since the adapter is set outside of the connection parameters. What I eventually discovered was that according to Zend_Db, the params key isn't limited to the connection. It also encompasses the driver settings. So in order to set my PDO driver settings to the way I want them to be, I ended up doing:

database.params.driver_options.PDO::ATTR_PERSISTENT=true
database.params.driver_options.PDO::ATTR_ERRMODE=PDO::ERRMODE_EXCEPTION
database.params.driver_options.PDO::MYSQL_ATTR_USE_BUFFERED_QUERY=true
database.params.driver_options.PDO::ATTR_DEFAULT_FETCH_MODE=PDO::FETCH_ASSOC

I think I'm going to have a lot of fun with my config ini in the future.

posted by chance at 12:21 pm  

Powered by WordPress