selfcontained[web development]

Articles tagged with "php" (8)

markdown.me

Friday July 8, 2011
By Brad Harris

Markdown is a great shorthand syntax for creating HTML, and subsequently, for taking notes. I often take notes for different situations and use the Markdown syntax to help give them structure and organization. One thing I found I often wanted was a way to enter that Markdown somewhere, and have it generate an HTML page from it, with a permalink so I could share it or access it later. The Markdown dingus provides a great UI for testing out HTML conversion, but doesn't provide any persistence, so I threw together a pretty quick site that fit my needs.

markdown.me

It's pretty basic, but you can throw in your Markdown and you end up with a unique url you can share with the generated HTML. I was too lazy to add a full-blown account registration layer to organize and manage your documents, but did add Facebook login so you can do that if desired. Perhaps I'll add other forms of login if anyone else ends up using it. Anything you put on there is public as well, for now. Here's the permalink to some notes I took at this year's Velocity Conference.

PHPUnit, Mocks and Closures

Saturday May 28, 2011
By Brad Harris

I like PHPUnit, and I like closures, but haven't found many useful cases for them (closures) in PHP yet. Just recently I came across a situation where I needed a closure when working with PHPUnit Mock objects. For those not familiar with Mock Objects in regards to testing, here's a link. It's fairly common when creating a mock object for testing to specify what a function is expected to be called with, and what it will return in that case. Below I'm creating a mock 'User' object that will return 18 for the age however many times it is called.

class UserTest extends PHPUnit_Framework_TestCase{

    public function testGetAge() {
        $user = $this->getMock('User', array('getAge'))
            ->expects($this->any())
            ->method('getAge')
            ->will($this->returnValue(18));
        $this->assertTrue($user->getAge(), 18);
    }

}

This is a pretty straight forward example of Mocks, but what happens when the value you want to return is dependent on the value it is called with, and there is some logic required to process this? This is where closures come in handy. Let's say you have a dynamic array you've built up, and you want to return true if a particular function, hasValue is called with a value that exists in that array. Here's how you can do it with Mocks and closures, using the returnCallback functionality of PHPUnit:

class UserTest extends PHPUnit_Framework_TestCase{

    public function testInArray() {
        $values = array(1,10,78,30);
        $user = $this->getMock('User', array('hasValue'))
            ->expects($this->any())
            ->method('hasValue')
            ->with($this->anything())
            ->will($this->returnCallback(function($value) use ($values){
                return in_array($value, $values);
            }));
        $this->assertTrue($user->hasValue(10));
        $this->assertTrue($user->hasValue(99) == false);
    }

}

When I call hasValue, passing in 10, we'll get true, and with 99 it's false. This is checked at runtime when the closure is executed, checking against the $values array. Also, stay away from Canvas Rider, it's dangerously addictive.

PHP and an abstract Singleton

Wednesday April 20, 2011
By Brad Harris

PHP is quirky. I've heard it called other things, but I'll leave it at that. I had a great learning experience while writing an abstract singleton class. Static binding in PHP behaves uniquely, and is often a hurdle when you try and develop an kind of an API using inheritance and static properties. If you aren't familiar with static binding in PHP, read the doc on late static binding and it will give you a good overview. This issue came up while creating an abstract singleton class.

Let me explain by example. Here's my first pass at a simple abstract singleton class that I could theoretically extend from other classes, and just pick up "singleton" behavior. Disclaimer!!! Don't use this class, it doesn't work!

abstract class Singleton {

    private static $instance = null;

    final public static function getInstance() {

        if(static::$instance === null) {
            static::$instance = new static();
        }
        return static::$instance;
    }

    protected function __construct() { }

}

This worked, initially, until I created two classes that extended Singleton and found the second one I called behaved remarkably like the first one.

class FirstSingleton extends Singleton {
...
}
class SecondSingleton extends Singleton {
...
}

Any calls to SecondSingleton::getInstace() were really just returning the FirstSingleton instance. Since the private static $instance property is delcared on the abstract Singleton class, there was really just one $instance being stored across calls to getInstance() from various subclasses. PHP doesn't bind the $instance property to the called class, it is bound to the class where it is declared, Singleton in this case. You could declare the $instance property on all classes that extend Singleton, but that is defeating the point of the abstract class. Here's round two, which does work, but I have mixed feelings about:

abstract class Singleton {

    private static $instances;

    final public static function getInstance() {
        $className = get_called_class();

        if(isset(self::$instances[$className]) == false) {
            self::$instances[$className] = new static();
        }
        return self::$instances[$className];
    }

    protected function  __construct() { }

}

The change here is that instead of storing a single $instance property on the abstract Singleton class, we're storing an array of instances, indexed by the class name of the called class. It behaves as expected, but the code isn't as clear or clean as I would have hoped it would be.

Latest Endeavor: whoopdwhoop.com

Sunday January 23, 2011
By Brad Harris

My wife and I have been chugging away on a new endeavor for awhile, and we finally got to a point where we could launch it live. In short, it's a currency free, creative marketplace, and it's called whoopdwhoop.com. It gives "artisans", or crafty people, a place to list their creations, and hopefully, a community where they can swap their creations with others all without exchanging any currency. This is facilitated through a pretty simple "whoop" (read point) based system. As people request a creation from someone, they pay them in "whoops", and then that person can use those "whoops" to request other creations. We haven't pushed much of a marketing campaign at it yet, in hopes to gauge initial feedback before doing so, and fix or improve whatever came up. We've done a fair amount of that so far, and are pretty happy with it's current state. Needless to say, we can't speak to if it will catch on and be the start of a thriving community, we'll have to wait and see.

While I don't think the majority of my blog's reader-base would be interested in using the site itself, I wanted to make a quick post to point out how the development of it has gone, which will hopefully be of more interest to those reading.

I built the site in about 4 or 5 months of actual heads-down, after-hours work. I have a day job, so this is just something I've spent nights and weekends putting time into. It's built on Zend Framework MVC, which I absolutely love. The UI is enhanced through YUI, which is another favorite library of mine. The database is MySQL, and I'm also using Doctrine ORM.

Zend Framework and Doctrine, in my mind, are a great marriage of libraries for PHP. Zend handles everything I've needed from an MVC, with the additional benefits of providing out-of-the-box API's for things like ACL, Auth, Caching, Emails and Logging. Doctrine does a great job at providing a stable and solid ORM, and a great means of managing updates through a simple migration strategy. The best part about finding a solid framework you enjoy working with, is you eventually end up with a great set of features you've built that can be dropped in to any project, giving you quite the head-start. When I started ( which was actually over a year ago, my motivation comes in spurts), Doctrine 2 was in development, but wasn't where it is now. I like the concept they've taken with the new version, but currently I'm using their 1.x version.

YUI is being used pretty sparingly right now. I think the only modules being used currently are containers for the dialogs, buttons, and menu. I need to give a shout out to the Minify library as well, which is handling the JS/CSS minification quite nicely.

I have some follow-up posts I plan on writing to go into more detail on some of the items and techniques I used in regards to things like Caching, but until I've had more of a chance to put the site through a ringer, I'll hold off. Anyways, if you're building a new site, looking for frameworks, I highly recommend everything I mentioned above.

?: PHP Coalesce

Tuesday November 30, 2010
By Brad Harris

I've often been a fan of Javascript's way of using the logical OR operator as a coalescing operator, or way to default values. It's a very handy operator for shortening ternary expressions.

var myValue = someOtherValue || true;

I just found out in PHP 5.3 they added an operator to do just that. ?:

$myValue = $someOtherValue ?: true;

That's all, carry on.

http://www.php.net/ChangeLog-5.php#5.3.0

Yahoo! A New Adventure

Friday October 22, 2010
By Brad Harris

My family and I are getting ready for a new adventure in our lives. We'll be moving to Denver where I'm super excited to go work for [Yahoo!][yahoo] and the Associated Content team. Getting a chance to work for Yahoo, and live and work in the Denver area is the perfect culmination of opportunity and lifestyle that my family and I have been waiting for. The work and product that the Associated Content team has created, and is developing is something I'm looking forward to being a part of. With every career move come new experiences and opportunities to learn and contribute, and I'm sure this will prove the same. On a technical note, I'll get a chance to continue using the technologies I love, PHP, MySQL, and some HTML/CSS/Javascript goodness. On a non-technical note, if anyone is looking for a house to buy in Rio Rancho, New Mexico, I know a great one for sale!

Doctrine Model Hydration

Tuesday March 30, 2010
By Brad Harris

I was just deep into figuring out what was causing a certain bug and wanted to take the time to share my findings. When working with Doctrine we were having some scattered issues of models that we had loaded from the database, modified, and then they were getting stomped on by the database again before saving, wiping out all modifications we had made. In this particular case we changed one attribute of a model, then called save. Our save triggers some validation that checks quite a few relationships and business rules between them. Somewhere in that process, a new copy of the model we were trying to save was being hydrated from the database, and overwriting our previous version. This seemed like pretty odd, and unwanted behavior, especially in our situation.

After digging around Doctrine's documentation and user group a bit, I came across an attribute setting that enables/disables this exact feature, Doctrine::ATTR_HYDRATE_OVERWRITE. By default this is set to true. If you hydrate a model from the database, and then somewhere later grab that same model through a reference, or a request to the Doctrine_Table, it will overwrite the model that is currently in memory for that key with a clean one from the database. Setting this attribute to false was a great fix for us, and ensures our code will run as intended.

$doctrine = Doctrine_Manager::getInstance();
$doctrine->setAttribute( Doctrine::ATTR_HYDRATE_OVERWRITE, false );

PHP Sessions in the db

Thursday May 3, 2007
By Brad Harris

I read an article today that I thought was great, and may be the answer to some oddities I've experienced lately. I host my sites on a MediaTemple GridServer account. Occasionally, as I'm logged into a site I've done, my session seems to just get blown away, and I lose my log in credentials. I noticed this recently as I was working on AdroitAuthentication class and trying to clean up how I was handling user authentication. I added in cookie handling to allow automatic logins if desired, and this seems to have alleviated the problem I was having with dissapearing sessions. Anyways, back to the article I read...

Storing PHP Sessions in a Database

This article described how a common problem with a multiple server environment, which helps for load balancing, is that sessions in PHP are by default stored on the hard disk. As you bounce around servers from load balancing, those files may not get copied with you, thereby causing your session to either be non-existent, or stale. A solution is to change PHP to use the database for sessions instead. Its a great article, and I'm going to give it a shot tonight and make it a feature in Adroit php framework. After excitingly discussing this with a co-worker of mine, he smiled at me and said he wouldn't comment on how Rails has that built into it already. Its funny how the more I develop Adroit, the more Rails-like features I find myself implementing... One day I'll give Rails a shot, but I really love PHP and without people pushing the envelope with it it won't progress as a language.