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!

Running PHPUnit on Remote System from Command Line

If I need to run PHPUnit on a remote system against a code suite, I will write a simple shell script like the following to do it for me. (Bonus points, you can even include this as an External Tool in eclipse to do it right from your project).

1
2
3
#!/bin/bash

ssh developmentserver "cd /var/www/tests && phpunit $1"

So, two things you should know: I’m using shared keys and have my .ssh/config file set up to have developmentserver as a name for the connection.

Bonus:

To add this as an external tool in Eclipse, do the following:

  1. Open Eclipse
  2. Click Run -> External Tools -> External Tools Configurations
  3. Double click ‘Program’ to create a new program.
  4. Name it to reflect the unit test you’re going to be running.
  5. In the location box, put the full location to your bash script
  6. In the arguments box, click Variables. Choose ‘selected resource location’
  7. Click Apply/Close

Now, assuming that your workspace is matched up to your file system on the remote system, you can run the external tool for PHP Unit on any selected test or folder. The output will appear in your console tab.

Posted in Eclipse PDT, phpunit | Tagged , | 1 Comment

Mod Rewrite to index.php file, the easy way

How many of you have written this before (or something very much like it):

?View Code APACHE
1
2
3
4
5
6
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

You might recognize something like this from the Zend Framework .htaccess file. Basically, the point is to say if something doesn’t exist, point it to the index.php file. Well, there is a simpler way to do this – I can’t believe I didn’t know this till now…

Apache Fallback Resource

All of that configuration now becomes this:

?View Code APACHE
1
FallbackResource /index.php
Posted in apache | Tagged | 1 Comment

Add PHPUnit Listeners to Watch for Long Running Tests

One of the under-utilized features of PHPUnit probably is the listeners interface. You can see the configuration options here: http://www.phpunit.de/manual/current/en/appendixes.configuration.html. So, I decided that I want to use this to know if a Unit Test takes longer than 2 seconds to run. That’s super over-kill in my opinion, but that’s my hard limit. If it takes longer than 2 seconds to run, something is wrong! So, I added the following to my configuration:

excerpt from phpunit.xml

1
2
3
    <listeners>
        <listener file="scripts/TestTimesLimitListener.php" class="Application_Test_TestTimesListener" />
    </listeners>

This simply says to invoke the listener from TestTimesLimitListener.php – which class name is Application_test_TestTimesListener. Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
 * Listener Class for test times
 *
 * @package Tests
 */

class Application_Test_TestTimesListener implements PHPUnit_Framework_TestListener
{
    /**
     * Number of seconds that this test can run
     * @var integer
     */

    const TEST_LIMIT_TIME = 2;
   
    /**
     * called when test is ended - determines if it was long and prints
     * @param PHUnit_Framework_Test $test
     * @param float $length the length of time for the test
     */

    public function endTest(PHPUnit_Framework_Test $test, $length)
    {
        if ($length > self::TEST_LIMIT_TIME) {
            $this->_printError($test->getName() . " ran for {$length} seconds");
        }
    }
   
    /**
     * Used to print error in error colors
     * @param string $error
     */

    protected function _printError($error)
    {
        print "\n\033[41m" . $error . "\033[0m\n";
    }
   
    /**
     * Required for Interface
     * (non-PHPdoc)
     * @see PHPUnit_Framework_TestListener::startTest()
     */

    public function startTest(PHPUnit_Framework_Test $test) {}

    /**
     * Required for Interface
     * (non-PHPdoc)
     * @see PHPUnit_Framework_TestListener::addError()
     */

    public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) {}

    /**
     * Required for Interface
     * (non-PHPdoc)
     * @see PHPUnit_Framework_TestListener::addFailure()
     */

    public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) {}

    /**
     * Required for Interface
     * (non-PHPdoc)
     * @see PHPUnit_Framework_TestListener::addError()
     */

    public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time){}

    /**
     * Required for Interface
     * (non-PHPdoc)
     * @see PHPUnit_Framework_TestListener::addSkippedTest()
     */

    public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) {}
   
    /**
     * Required for Interface
     * (non-PHPdoc)
     * @see PHPUnit_Framework_TestListener::startTestSuite()
     */

    public function startTestSuite(PHPUnit_Framework_TestSuite $suite) {}
   
    /**
     * Required for Interface
     * (non-PHPdoc)
     * @see PHPUnit_Framework_TestListener::endTestSuite()
     */

    public function endTestSuite(PHPUnit_Framework_TestSuite $suite) {}
}

First of all, the class must implement the PHPUnit_Framework_TestListener interface. That’s why at the end you’ll see all the extra empty methods piled on. Let’s dive into the code:

Define a constant of the number of whole seconds. Next, define the endTest method which will receive a float of how many seconds/milliseconds that test took to run. If it takes longer than our limit, print an error using the test name. The _printError() method uses some control characters to change the font color red.

There you go! Now, during your normal execution of unit tests, you may see a few warnings for long running tests in red. Go and correct those to keep your tests running smooth and fast.

Please note: a while ago, I ran into a blog entry about this. It wasn’t clear to me at the time, so I didn’t book mark it. However, I wanted to mention that this isn’t 100% only my work. Credit to where credit is due.

Posted in phpunit, testing | Tagged , | Leave a comment

Setting PHP Command Line Colors

I’m not entirely certain why this escaped me for so long, but it’s remarkably easy to set terminal colors with PHP. Simply echo the escape/color character \033, followed by the bash color definition and your output. For reference, here is a listing of bash colors. So, for example, if we want to make something blue text, do the following:

1
echo "\033[34m" . 'here is blue text' . "\033[0m\n";

This simply sets the blue color, adds the blue text, and then resets the color to default, and makes a new line.

Posted in PHP | Tagged | Leave a comment

When you Create Your Account, Please log in.

I’ve always found it annoying when programmers create systems where you create your account and then you’re not logged in. Maybe I’m lazy? I decided to do a poll on a popular social networking site. The poll went like this:

When signing up for a new web site, do you mind logging in after signing up?

The two options were:

  • If I create an account, it should already log me in.
  • I don’t mind logging in after I create my account (it proves I know my password)

Overwhelmingly (ok only 78% but still…) response has been in favor of creating an account and logging in automatically. I think that we should take the extra step when creating applications to make this process streamlined for users.

Posted in Misc Web Design | Tagged | 2 Comments

Zend Framework Authentication: Let the user know if it is their fault

One of the things that is irritating is logging into a website with credentials that you know are right, only to have it fail. Then, later, you find that the site was malfunctioning. By then, maybe you requested a new password, or had to at least waste time looking up your old password. With Zend_Auth, however, we can prevent user’s from having that issue.

Side note: some schools of thought want to go the extra mile for security and never give the visitor any extra information than what is required. I believe this to some extent. I will say the username or password is wrong (I won’t say that the username exists, but the password is wrong.) However, I don’t think it’s out of line to alert the user if your system is having authentication issues.

So, with Zend_Auth, the authenticate() method returns a Zend_Auth_Result. This, of course, has the isValid() method which everyone is familiar with. However, there are a number of reasons why this could return false. Whatever reason generated the invalid response will be returned by the getCode() method. These include:

    const FAILURE                        =  0;
    const FAILURE_IDENTITY_NOT_FOUND     = -1;
    const FAILURE_IDENTITY_AMBIGUOUS     = -2;
    const FAILURE_CREDENTIAL_INVALID     = -3;
    const FAILURE_UNCATEGORIZED          = -4;

The user is really only concerned with the FAILURE_IDENTITY_NOT_FOUND and FAILURE_CREDENTIAL_INVALID conditions. The rest are more-than-likely our own failures. (For example, your data has become corrupted? FAILURE_IDENTITY_AMBIGUOUS).

When I generate error messages for the user, I tend to make a method called isFailureUserBased() which will determine the type of error I return. If it is user based, I’ll return a string saying incorrect username or password. If it is not user based, the message will be to contact support or wait it out (I might even send an automated note to the support staff at this time).

This is usually a very simple method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
 * Used to determine if this is a user failure or an internal failure on our part
 *
 * @return boolean if its a user failure
 */

public function isFailureUserBased()
{
    $result = $this->_authResult->getCode(); //stored internal Zend_Auth_Result instance
   
    switch ($result) {
        case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
        case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
            return true;
    }
   
    return false;
}
Posted in zend framework | Tagged | Leave a comment

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 , | 1 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 , | 3 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