Aaron Saray

open source programmer,
web developer

entrepreneur, author
and musician

My Blog

contains PHP, Web and business/entrepreneurial related content. Please join in the conversation!

Presenting at Joomla Day Midwest

Hello all. It’s been quite the long time since I updated my blog. I know, I know, this is a huge problem, considering this is a cardinal sin according to my talk at MKEPUG about getting job offers. That was wrong, I know. However, things have been pretty busy. Let’s see…

A) Finished up my presentation for Zend about Zend Filter

B) Studying for the Linux+ exam (While I’m still doing some college classes, I also keep up on my certifications.)

C) Ran over to Madison to do a presentation on PHP Design Patterns.

D) Working with Joel to bring on a new MKEPUG leadership team and working with Steve to help on the Web Design Meetup.

E) … and now, I’m presenting about

Cloud Hosting and SaaS at Joomla Day Midwest.

Update! Presentation can be downloaded: Here (PDF)

Hope to see people out there. Make sure to DM me on Twitter if you want a discount code (Yup, you’d be a super late-bird but still save $25!).

Oh – and make sure you stay tuned. New topics coming out shortly on the blog including:

  • More PHPUnit testing methodologies
  • Leadership for PHP Programmers
  • Filters for Zend Framework
  • Writing good auditing for your applications
  • ACL’s in PHP and Zend Framework
  • Masking Credit Card Information
  • and more!
Posted in learning | Tagged | Leave a comment

Testing protected and private attributes and methods using PHPUnit

First, I just want to say up front that this is not a discussion of “is 100% test coverage necessary” or a discussion about testing private methods. This is simply how you may do it if you wanted to.

Testing Protected/Private Attributes using PHPUnit

PHPUnit has this built in – simply use PHPUnit_Framework_Assert::readAttribute(). So, for example, lets say our object User has a protected role id of 1.

1
2
3
4
5
public function testUserRoleIsOne()
{  
  $user = new User();
  $this->assertEquals(1, PHPUnit_Framework_Assert::readAttribute($user, '_roleId'));
}

Testing Protected/Private Methods in PHPUnit

This method is mainly reflection based. The PHPUnit component is really only the testing. Lets say a protected method _getKey() of the User object returns a value of ‘mysuperawesomekey’

1
2
3
4
5
6
7
8
9
10
  public function testRetrieveKeyFromUser()
  {
    $user = new User();

    $reflectionOfUser = new ReflectionClass('User');
    $method = $reflectionOfUser->getMethod('_getKey');
    $method->setAccessible(true);

    $this->assertEquals('mysuperawesomekey', $method->invokeArgs($user, array());
  }

This code creates a new object of our object that we’d like to test. Then, it creates a reflection of it and its method that we want to test. Next it sets it to accessible. Finally, in the assertion, the invokeArgs() method of a reflectionmethod is called using the object instance to call it. The empty array() is because this method does not accept parameters. If your method did, you would put them there.

In my code, I add a static method to handle most of the testing setup for protected/private methods to a helper class so I don’t have to duplicate the above code.

Posted in Test Driven Development | Tagged , | Leave a comment

Service Class Methodology

There has been a lot of discussion on forums and throughout the object oriented PHP programming community about service classes. This is just intensified by the Zend Framework model of development coupled with the changes in their design/architecture and vocal spokespeople. I thought I’d throw my hat in the ring for this.

Disclaimer: I have been programming PHP for a decade. I have been programming in general for nearly 2 decades now. I am not a comp-sci university graduate, however.

First, its important to understand the basis of what I’m calling a service class. When I develop, I consider a service class as something that takes an object and manipulates it. So, its important to understand that a typical ‘model’ should be a business object. For example, a User is a business object. This user may have different traits: name, email, role, etc. This object is dumb, however. It should only know about itself. It can have logic: it might have a method called createFullName() which means it understands the relationships of its firstName and lastName variables and can combine them intelligently. However, beyond that, it does nothing else special except have identity.

The service class can be somewhat coupled to the business object. So, I might have a UserService class. This is bound to the User object. This service class understands how to create User objects, how to edit them, etc. This service class understands the origin of the object – for example, the database. It is responsible for formulating a business object out of data it retrieves. (This gets into a very indepth discussion. In this example, I’m going to just have my service classes have one method of retrieving data. However, the retrieve data method could have many adapters including database, web service, memory/cache, etc). So, this service is responsible for the object, so that the object doesn’t have to be.

The service handles the object from initialization through all manipulations up until interpretation. This is to say that the service class has the functionality to retrieve the data to create the User object, can manipulate it, can save it, and then finally can present it to a display layer to show results. One thing that can be confusing is what should happen when something is directly coupled with this User object. So, if a change happens to the user, and then this triggers another change that should happen to it, the user object (business object) should never be given up. It shouldn’t be exported. Instead, adapters and strategy patterns should be implemented. That isn’t to say that the user object can’t be available for query – say to get status or name – but it shouldn’t be passed on. The service class should handle one whole business process. If this process changes, changes can be applied through adapters, different strategy or even observers. There should never be a time when a whole process that effects one object with change requires two services to handle the object. Don’t get this confused with one whole process requiring more than one service however. And these services can even query the object, they just can’t retrieve/transfer it or change it.

The real life example of this could come in the form of a Zend Framework example. Lets say I have users on my website which are mapped to the User mysql table.

First, for Zend Framework, I’m going to make a connection using ZF’s database services. This will be used later for loose-coupling in the service:

1
2
3
4
class Application_Model_DbTable_User extends Zend_Db_Table_Abstract
{
    protected $_name = 'user';
}

Next, I’m going to create a User object. (You may notice some examples make the business object extend Zend_Db_Table_Rowset or similar classes. This is coupling our object way too tightly to this particular data retrieval. Our business object model shouldn’t know about that!)

1
2
3
4
5
6
7
8
9
10
11
class Application_Model_User
{
  public $id = 0;
  public $firstName = '';
  public $lastName = '';

  public function getFullName()
  {
    return $this->firstName . ' ' . $this->lastName;
  }
}

In this example, I’ve added some business logic – creating a full name.

Finally the service class would be needed to be created. In our example, I’m going to demonstrate retrieving user row #100

1
2
3
4
5
6
7
8
9
10
11
12
13
class Application_Model_UserService
{
  public function getUserById($id)
  {
    $table = new Application_Model_DbTable_User();
    $resultArray = $table->find($id)->current()->toArray();
    $user = new Application_Model_User();
    foreach ($resultArray as $key=>$val) {
      $user->$key = $val;
    }
    return $user;
  }
}

Of course, as you add more functionality to this service class, some of this logic an be removed to re-usable functions with your standard refactoring methods. (For example, caching the instance of the dbtable, etc). This example also doesn’t handle issues where maybe that value isn’t handled.

The point of this example is simple: See how the service class handles creating the user object, handles getting the data, and assigning it? This means that the data can come from a different source at any time (we could create a complex adapter system so it could easily be swapped out). Also, the user object could be created from any data set, not just a table request, because it doesn’t know any better.

Through trial and error, these are my thoughts on Service classes. Have any input? Would love to hear how you work.

Posted in programming, zend framework | Tagged , | 2 Comments

Zend Framework Front Controllers vs Bootstrap: Round 2

This article is the follow-up to the original article.

There was some discussion on Twitter regarding the original version of my article about putting most of your site’s setup in the front controller plugins in Zend Framework. However, I haven’t seen a lot of real reasons except for “that’s what the example says” or “this is how I feel.” These suggestions I have are based on performance and logical reasons. However, I could be wrong or maybe I was unclear. So I did a bit more research and I have just a few more notes.

When Initializing Site in Front Controller, Use the Proper Hook

So I started examining my example code. I noticed how I added a lot of code to the routeStartup(). My initial thought was that almost everything should be here. Perhaps I define routes depending on the permission of the current user. I need to initialize my ACL right away to know if I can allow access to other resources. I also wanted to make sure the view was available because certain controllers could update or modify it.

But, I realized I was piling too much stuff into the method. Let’s think of this example:

  1. User visits site.com/admin
  2. Front Controller plugin launches before we determine the route and initializes all items for this admin page.
  3. ACL Plugin or Admin Controller init() method determine that the user doesn’t have access to this page and sends a redirect.
  4. User is redirected to site.com/login and the entire process from #2 begins again.

Well this doesn’t sound too bad until I realized that I initialized my view settings and other resources before I issued a redirect. This shouldn’t be. Instead, I should have been smarter about this.

What Should Go Where in the Front Controller Plugin Site Initialization

First, routeStartup should have all the resources that will always, always be used no matter what. It is also a place to initialize things that may cause the site to redirect, handle errors, logging, or permissions of routes. Things like the view settings should not be initialized here.

Next, dispatchLoopStartup would be a good place to apply any modifications or initialization to things like the view. This is before the dispatch starts, so it makes these resources available for all of the action methods. Now, this isn’t 100% free of still experiencing things like redirects but its close. (We could still issue a redirect at the end of a method).

Finally, dispatchLoopShutdown would be for initializing other resources that will only happen when a user is viewing a webpage and has little to no dynamic value. For example, Google Analytics initialization or something similar. (Very rarely do I find myself actually putting anything in here. Even my GA is created in a view helper instead).

What Problems Can This Cause?

There are two possible problems I’ve ran into with this. First, the programmer can make a mistake by putting the wrong resource in the wrong hook. This will happen from time to time. Not the end of the world! The second problem is a bit more deeper: Using PHPUnit to test Controllers. When testing controllers, the test will extend Zend_Test_PHPUnit_ControllerTestCase. This class has a setUp() method that re-initializes the request on each test method call. This means that the bootstrap is reset. All of the examples show running your bootstrap again in there instead. However, if you bootstrap each method with your bootstrap, and then the controllertestcase class resets the front controller request, only half the of the request is valid. This is confusing yet and something I’m aiming to fix in my test classes. I’ll post more when I have this figured out. Long and short of it, the Zend_Test_PHPUnit_ControllerTestCase class seems to be set up requiring/expecting that your bootstrap is in the traditional version.

What’s your input?

Do you see positives or negatives of this setup? Would love to hear your thoughts.

Posted in zend framework | Tagged | Leave a comment

Testing Outgoing Email with Zend Framework

I was creating a new application with Zend Framework at work the other day and I started using my technique that I described here by adding the original email in my email address using the + sign. However, the current organization I’m at has a mailserver (Exchange?) that is either configured not to allow this or just doesn’t have this functionality built in. So, this won’t work. I solved this with a new implementation of the mail class.

Goals/Objectives

  • Using Zend Framework’s Zend_Mail to send mail
  • Must send to me in non production but I should be able to verify who the original recipient would have been
  • Must require no changes between production and development code – should be automatic

The Solution: A new class Application_Model_Mail

I decided to make a new model called Mail which will extend the Zend_Mail class. Everything will work the same except for the to addresses. See this code: application/models/Mail.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Application_Model_Mail extends Zend_Mail
{
    public function addTo($email, $name='')
    {
        if (!is_array($email)) {
            $email = array($name => $email);
        }

        if (APPLICATION_ENV !== 'production') array_walk($email, array($this, '_convertToTestEmails'), $this);        
       
        return parent::addTo($email);
    }
   
    protected static function _convertToTestEmails(&$email, $key, $mail)
    {
        $testEmail = 'test@developer.com';
        $mail->addHeader('X-Test-Original-Email', $email, TRUE);
        $email = $testEmail;
    }
}

First, the addTo() method is overwritten. A bit of the code is copied in order to determine if the email address is an array with the name=>email key or just an email. The end result is $email as an array with a key of the display name (possibly blank) and a value of the original email address. Next, check the application environment. If it is not production, array_walk the email array using our protected _converttoTestEmails method. Finally, call the parent addTo() method using the new $email value that has been processed.

The protected function _convertToTestEmails() gets the destination developer email address. Then, it adds a header of the original email address. Checking this header is how I can verify, if necessary, that the original email address would have been right. Then, it replaces the original email address with the test developer address. Notice, it keeps the key the same. This means that during the testing process, the developer could get multiple emails sent to them with different ‘to’ names but always the developer’s email address. To fully verify, the X-Test-Original-Email needs to be verified.

Do you have any ways that you use besides my original method and this to test emails?

Posted in testing, zend framework | Tagged , | Leave a comment

Zend Filter Presentation

Thanks to Zend and their community organizers for the opportunity to do a webinar today.

I have uploaded my slides from the presentation here: Zend Filter Presentation

Posted in zend framework | Tagged | 1 Comment

Adding Subdomain Routes for all URLs in Zend Framework

All the examples I’ve seen for pulling information from subdomains are from the hostname router directly correlating one subdomain as a value to a single controller/action combo. This means they map username.website.com to something that basically looks internally like website.com/user/profile/var1/username. This is cool for simple one off tasks – however, what if you’re creating a multiple controller/action solution? For my example, I’m creating a CMS that will have a shared code base. However, on every page, I need to know exactly which site this is.

Enter Chaining!

So far, all the examples have shown how to chain a hostname route to a single other route. Like I mentioned, this solves the singular subdomain->action connection. However, now I need to apply it to all of my routes.

In my example, I’m going to make sure that the following code is at the very end of adding all of my other standard routes. If someone adds a route AFTER this code, it will not work correctly for their routes.

Use the following code:

1
2
3
4
5
6
7
8
$router = Zend_Controller_Front::getInstance()->getRouter();

$hostnameRoute = new Zend_Controller_Router_Route_Hostname(":sitename.example.com");

$router->addDefaultRoutes();
foreach ($router->getRoutes() as $key=>$route) {
  $router->addRoute('hostname' . $key, $hostnameRoute->chain($route));
}

First, the router is retrieved again. Next, the hostname route is created. In this case, our domain is example.com. I want to have a parameter called sitename in my controllers. Next, I force the router to add its default routes right now. Normally this is done after custom routes. Finally, each route that now exists, the default routes, the custom ones you’ve written, etc, are all looped through. A new route is added which is basically named after that route with the prefix of ‘hostname’. The route is a chained version of the original with the hostname.

Now, when visiting site1.example.com/blog/add, the parameters array in the controller will be:

'sitename'=>'site1',
'controller'=>'blog',
'action'=>'add'
'module'=>'default'
Posted in zend framework | Tagged | Leave a comment

Zend Framework: to include or not to include

There are two ways of working with Zend Framework as a library in your project. These are including it in your project repository and using a shared copy on the server (like PEAR). Let us discuss both:

Including Zend Framework In Your Project

The first method is to include the Zend Framework library folder in your zend framework project’s library folder (uh….). So, for each project on your server that is built on Zend Framework, the following path has a copy of Zend Framework: /root/to/your/app/library/Zend. This means each project has at least the entire size of the Zend Framework in it. Pros/Cons?

  • Pro: Can control the exact version of Zend Framework with this project. A server zend-framework upgrade won’t potentially hose up your project.
  • Con: Have to update ZF in each project on the server when an update comes.
  • Con: Takes up considerable space in the code base.
  • Pro: Easier IDE configuration. It can find all the code easily in this project (true: you could configure your IDE to use other libraries that aren’t in the project)
  • Pro: Migrating to a new server, just one less thing to consider when setting up. Code with the ZF in it is fully contained and deployable anywhere.

Using Zend Framework as a server wide install

Like PEAR, Zend Framework can be installed on the server in a shared location. You may install your Zend Framework Library folder into a different path, for example: /root/to/shared/code/Zend. Then, your PHP has to be configured to have that in its include path. Pros/Cons?

  • Pro: Any project at any location on your server has access to Zend Framework. As you know, you can only pick pieces of ZF to use, like the PDF functionality. May make it easier to transition project from legacy code to ZF.
  • Pro: When an update comes, it can be applied only one time to the shared location.
  • Con: Updating shared code could break an application – all need to be tested with new code.
  • Pro: Save code space in your code repository.

Currently, I’m going with including it each project as a point of preference. I think the risks outweigh the possible time/storage savings. So, what are your thoughts?

Posted in zend framework | Tagged | 4 Comments

Forcing UTF-8 in Zend Framework with PDO

For some reason, I just had the most horrible time making sure that my connection from my Zend Framework code was speaking UTF8 at my database. Here are the key things to remember that I learned:

  • Make sure to have a collation of UTF8 on your database
  • Set your default charset on your table is UTF8
  • Zend Framework Zend_Db_Mysql uses PDO – so use PDO commands when you create your connection to force UTF8

Ok first thing’s first. Create the database with the proper collation:

1
CREATE SCHEMA `mydatabasename` DEFAULT CHARACTER SET utf8;

Next, define your tables with UTF8 charset:

1
CREATE TABLE `mynewtable` (`a` INT NULL ,`b` INT NULL) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8;

Finally, if configuring your PDO/MySQL connection in application.ini, after defining the connection parameters, as I have, add the last two lines

resources.db.adapter = "pdo_mysql"
resources.db.params.host = "localhost"
resources.db.params.username = "user"
resources.db.params.password = "password"
resources.db.params.dbname = "mynewtable"
resources.db.isDefaultTableAdapter = true
resources.db.params.charset = "utf8"
resources.db.params.driver_options.1002 = "SET NAMES utf8;"

I never had a chance to track down the reasons “why” this was happening – so if anyone has any input, that would be great. But now I add this to all of my projects just to force it.

Posted in zend framework | Tagged | Leave a comment

Useful Firebug Tricks with Zend Framework

Zend Framework has a few hooks with the Firebug browser plugin (with the firePHP add-on). The two that I use are writing logs to the console and profiling of database connections.

First thing’s first: Make sure to only enable these settings in your non-production environments.

Zend_Db profiling

One of the most helpful things I do for my database setup is initialize the Zend_Db profiler with firebug in my application.ini file. It is important to have this under the development section and nowhere else. Check out this snippet of my application.ini file:

[development : production]
resources.db.params.profiler.enabled = "true"
resources.db.params.profiler.class = "Zend_Db_Profiler_Firebug"
...

Logging Application Alerts to Firebug Console

I don’t like to check logs while I’m developing. I’d rather have all of these alerts in my face. Luckily, Zend Framework allows a firebug logger to do this for me. In my bootstrap.php file, I will create a method similar to this:

1
2
3
4
5
6
7
8
9
  protected function _initLogs()
  {
    $logger = new Zend_Log();
    if ($this->getEnvironment() != 'production') {
      $writer = new Zend_Log_Writer_Firebug();
    }
    $logger->addWriter($writer);
    return $logger;
  }

With this code, your log-able items can retrieve this bootstrap resource and it will write the messages right to the console. (Side note: Most of my applications actually have another part to that If statement where they define the production logging system including setting priorities).

Do you have any creative uses for Firebug with Zend Framework?

Posted in zend framework | Tagged | Leave a comment