ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

Latest Blog Entries rss.png


Throwing Custom Errors?

Monday, March 27th, 2006

In a recent article on PHPit I talked a bit on throwing your own errors, and what the best methods are, and I'm interested in what others think.

I use a lot of different (custom) libraries and components in my PHP scripts, and figuring out the best way to return errors is always a problem. The easiest way is to simply return false when something bad happens like so:

$data = load_file ('C:\my\file.txt');

if ($data == false) {
        echo 'Something bad happened';
}

function load_file ($file) {
        if (file_exists($file) == false) {
                return false;
        }

        // Load file data
}

?>

But this has several limitations, and provides no flexiblity at all. Another possibility is to use exceptions, like so:

try {
        $data = load_file ('C:\my\file.txt');
} catch (Exception $e) {
        echo $e->getMessage;
}

function load_file ($file) {
        if (file_exists($file) == false) {
                throw new Exception('File can\'t be found');
        }

        // Load file data
}

?>

But this only works if you're using PHP5 (and my web host doesn't support it yet) and you must catch the exception, otherwise a really ugly fatal error is printed. So that's not really a perfect solution either.

If you're library is built around a class, then something like this would be possible:

$lib = New MyLib;

$data = $lib->load_file ('C:\my\file.txt');

if ($data == false) {
        echo $lib->error;
}

Class MyLib {
        var $error;

        function load_file ($file) {
                if (file_exists($file) == false) {
                        $this->error = 'File can\'t be found';
                        return false;
                }

                // Load file data
        }

}

?>

This seems like the best solution to me, although it does have a few small drawbacks. For example, when using the load_file() function again, you have to clear any previous errors, or else errors could get mixed up.

In the article I also present another solution involving a static class, which is used as a global error stack, and it sort-of emulates exceptions. But that approach doesn't really work if you're using individual libraries.

So, any thoughts on this? Have I missed any solutions, which might work much better?

Ajax PHP function lookup

Wednesday, January 11th, 2006

Found this nifty utility through Digg.com: phpFunctions.

This is a simple Ajax script which works just like Google Suggest, except it looks up PHP functions. Type the first part of a function, and it will automatically find the functions that match, and when you've found the function you're looking for, it'll automatically display all the details (like arguments, description, etc).

Seems like a pretty cool use of Ajax, but I doubt I'll be using it a lot (or even at all). I find going to php.net/[function name] a lot easier and faster. It'd be pretty neat though if this could be built into some web based PHP IDE.

A Look At Livepipe

Friday, January 6th, 2006

A few days ago I got an e-mail from Ryan and Nicholas from Livepipe asking if I wanted to take a look at the first Developer's Preview of their new PHP framework, called Livepipe. I'm always interested in new stuff, so I just took a quick look. The framework is released under a MIT license, which means you can use it freely, so grab a copy as well if you're interested.

The framework comes with excellent documentation and a good beginner's tutorial, because you'd be lost otherwise. Just like all other frameworks (e.g. Ruby on Rails, Cake, etc) it requires you to create your PHP scripts in a certain style, which can certainly be confusing. But if you just follow the tutorial (how to build a blog in 15 minutes) you'll get it going. Just a word of warning though, there's a small mistake in the tutorial.

In the beginning where it says:

require_once('../system/runtime.php');
Controller::start('SimpleBlog','/blog/');

That should actually be:

require_once('../system/runtime.php');
Controller::start('Blog','/blog/');

So far the framework seems quite decent, and I definitely like the inbuilt SQLite support. I won't be actively using it myself, because I don't really like using frameworks, but if you're on the lookout for a good framework, give Livepipe a test run, and see what you think of it. Don't forget to report any bugs to the developers so it becomes even better.

Abandoning PHP4?

Monday, January 2nd, 2006

There's an interesting discussion over at SitePointForums over whether it's time to abandon PHP4, and code exclusively for PHP5 now. Just to pull some random quotes out of the discussion:

PHP4 is the norm in 100% of my projects right now. I'm not happy about it and would love to migrate as quickly as possible. It's just not happening fast enough. I would expect the big shift to happen some time this year.

No one knows, but as far as I'm concerned, PHP4.yuk is dead and buried. Let the celebrations continue

I sell a commercial application that requires PHP5. I think that sales have been hurt a bit by the fact that PHP5 support in shared hosting environments is far from ubiquitous. Right now I'm averaging about 2-3 sales per week with one in three buyers emailing me after the fact saying they just realized their host doesn't support PHP5 yet.

Not only that a very small minority of hosts use PHP 5. While everyone has fully accepted PHP 4. We need a better motive to switch.

Some say PHP4 is dead, others say it's still very alive and kicking, but the last two quotes really nail the issue. It isn't about whether we (developers) think PHP4 is dead, it's about whether the market thinks it's dead. I'm sure all us would love to code under the latest stable version of PHP5 (and PHP6 when it comes out), but if you can't control the environment your script is going to run in, you must make sure it works on almost any platform.

Seeing as how there are still a lot of web hosts who do not support PHP5 yet, it seems fairly logical to stick to PHP4, until at least 90% of the market has switched to PHP5. When will this happen? I have no idea, but hopefully sooner rather than later, especially with PHP6 coming sometime next year (2007).

I personally still code in PHP4, but I do make sure my scripts work under PHP5, which means I get the best of both worlds, and my scripts can be used on almost any platform.

PHP Unit Testing

Sunday, December 18th, 2005

Chris Shiflett has posted an interesting entry on Unit Testing in PHP, together with a PDF slideshow (Power PHP Testing - PDF link!).

The slideshow is actually quite interesting, because it goes through all the unit testing packages (like PHP-Unit, SimpleTest, etc) and reviews them. It also gives sample code for each package, which is a nice addition, especially if you're looking for a simple package.

I haven't done any unit testing myself yet, because I've never had to, and I wouldn't know how to do it properly, but I should probably start doing it soon, especially with my commercial projects (I do use a similar form of unit testing, except it isn't really unit testing).

Looking for a PHP gig? Yahoo wants you!

Saturday, December 17th, 2005

If you're PHP developer, you could be the person Yahoo is looking for. Via PHPDeveloper.org:

Title: Yahoo Web Developer for Small Business
Location: Sunnyvale, CA

Y! Small Business is looking for a self-motivated experienced Web Developer to join the Small Business engineering team. In this capacity, you will work closely with interaction designers, visual designers, user experience researchers, software engineers, and product managers. The ideal candidate possess a strong command of markup, PHP, CSS to level 2, JavaScript to version 1.5, practical knowledge and use of up to DOM2 methods and properties, cross-browser development techniques, browser degradation strategies, well-versed in code optimization and development patterns, accessibility 508 compliance guidelines, and experience with end-to-end high-quality development/testing. You will exercise innovation and influence in support of UI design and heuristics through your expertise in client development to enhance user experiences.

Experience working in Unix environments, CVS or source control, and bug tracking tools is highly desirable. The environment is fast-paced with numerous, user-centered, iterative design and development cycles. You will be responsible for creating proof-of-concepts/prototypes to production-level "best of breed" websites and applications.

If you think you've got what it takes, or if you just want more information, send an e-mail to teddi [at] yahoo-inc [dot] com for more information. If I was living in the Sunnyvale, CA area, I'd be applying right now!

Comparing strings in PHP

Friday, December 16th, 2005

Interesting entry over at Greg Beaver's blog today on comparing strings. Apparently, when you try to use the following code:


var_dump('01' == '1.');
?>

It will actually return 'true', even though '01' is definitely not equal to '1.'. The problem here though is that PHP automatically converts both strings to a number, and thus 01 becomes 1 and 1. becomes 1 as well. This isn't what we want though.

Greg gives a few solutions in his blog entry, but the best one is just to always use the type-specific comparison operator (===) instead of the regular one (==). The above code would then be:


var_dump('01' === '1.');
?>

And that does print out the correct result (false).

Interview with Chris Shifflet

Thursday, December 15th, 2005

CodeSnipers has posted an interview with PHP legend with Chris Shifflet today. It's a bit on the short side, but still interesting nonetheless. The first part of the interview goes over a few security issues in PHP, and the second part is more about Chris.

If you just want to know a bit more about Chris, or you're interested in PHP security (every developer should be interested in this), click here to read the interview.

Blog now in a seperate RSS feed

Sunday, December 11th, 2005

I've decided to remove all the blog entries from the main RSS feed, and it will now have its own RSS feed. The main feed will focus strictly on the articles, FAQ's and code snippets, whilst the blog feed will have all the blog entries, and be full-text (like any blog feed should be!).

If you want to subscribe to the blog feed, it's available at: http://phpit.net/category/blog/feed/.

Using an output callback and ob_gzhandler together

Saturday, December 3rd, 2005

If you've ever tried to use an output callback and ob_gzhandler together, you might've run into problems. Just try it yourself with the below code snippet:

function mycallback($buffer) {
        $buffer = str_replace ('Dennis Pallett', 'John Doe', $buffer);

        return $buffer;
}

ob_start('mycallback');
ob_start('ob_gzhandler');

echo 'My name is Dennis Pallett';

?>

The above code should replace 'Dennis Pallett' with 'Joe Doe', except it doesn't because of the ob_gzhandler. Remove ob_gzhandler, and it will replace the names.

To fix this, you must decode the buffer in your callback, then make your changes, and encode the buffer again (this last step is extremely important, or you'll get garbage). The only problem though is that PHP doesn't have a gzdecode function, only a gzencode function. Thankfully, this is extremely easy to write:

// Define the gzdecode function
if (!function_exists('gzdecode')) {
        function gzdecode ($data) {
                // Check if data is GZIP'ed
                if (strlen($data) < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) {
                        return false;
                }

                // Remove first 10 bytes
                $data = substr($data, 10);

                // Return regular data
                return gzinflate($data);
        }
}

All this function does is first check whether the data is actually gzip encoded, then removes the first 10 bytes, and finally uses the gzinflate function to do the actual decoding. I've used this function many times myself, and I've never had any problems with it.

The callback code now looks like this:

// Define the gzdecode function
if (!function_exists('gzdecode')) {
        function gzdecode ($data) {
                // Check if data is GZIP'ed
                if (strlen($data) < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) {
                        return false;
                }

                // Remove first 10 bytes
                $data = substr($data, 10);

                // Return regular data
                return gzinflate($data);
        }
}

function mycallback($buffer) {
        // GZipped buffer?
        $gzbuffer = gzdecode($buffer);
        if ($gzbuffer !== false) {
                $buffer = $gzbuffer;
        }

        $buffer = str_replace ('Dennis Pallett', 'John Doe', $buffer);

        // Return normal or GZipped buffer
        return ($gzbuffer !== false) ? gzencode($buffer) : $buffer;
}

ob_start('mycallback');
ob_start('ob_gzhandler');

echo 'My name is Dennis Pallett';

?>

If you now run the above code it will correctly replace the names, with and without ob_gzhandler enabled. I've used the above code in many of my scripts (most notable my PHP components), and it's worked perfectly.