Wednesday, November 28, 2007

ZF View Helper for switching between http and https

I created a view helper for Zend Framework for switching between a normal (http) and secure (https), as sugested by Naneau.

<?php
/**
* Helper class to switch between normal and secure protocol
*
*/
class Zend_View_Helper_HttpSwitch {

/**
* Property of our view instance
*/
protected $_view;

/**
* Get our view property
*/
public function setView(Zend_View_Interface $view)
{
$this->_view = $view;
}

/**
* Switches between http and https protocol
*
* @param array $route
* @param boolean $secure
* @return string
*/
public function httpSwitch(array $route, $secure = false)
{
// Hostname now set here, or in configuration file
// or set in the front controller.
// Zend_Controller_Front::getInstance()->getParam('hostname');
$hostname = "www.example.com";

// Check if we want to go secure or not
if ($secure === true) {
$protocol = "https";
} else {
$protocol = "http";
}
return sprintf("%s://%s%s", $protocol, $hostname, $this->_view->url($route));
}
}



Blogged with Flock

Monday, November 19, 2007

The new Zend.com website


Zend, the PHP company has a new website and a new logo. Although I'm not a graphical designer nor have I any graphical insight, my gut feeling tells me the new logo misses the flair other Zend sites (devzone.zend.com and framework.zend.com) have.

As for the new website, it's a huge improvement. A clear view on topics and a very easy navigation. Especially you can see how the technology works behind the scenes by clicking the right-top corner "Behind the Site". Don't expect much fancy stuff, it's just an explanation on how this site is managed by Zend products and the iBuildings CMS WDE. Both companies are working to port this CMS to PHP 5 and will be released in the nearby future.

Just see for yourself at zend.com.

Wednesday, November 14, 2007

Zend Framework Demo app

In my search for a good error control mechanism using Zend Framework, I stumbled on Andries Seutens' blog where he presented a simple, yet nicely written application to fetch feeds.

See for yourself on his blog.

Friday, November 09, 2007

Error handling in Zend Framework

For a couple of days I've been breaking my scull how to provide a good way to handle exceptions in a Zend Framework MVC application.

The ZF Manual has several ways of doing stuff, but none of them have a good example how to take care of these exceptions, and how to present a nice message dependend on the exception that was raised.

1. Using the ErrorHandler plugin
This is the easiest way of handling missing controllers, actions or modules. But it's usage is limited to these kind of exceptions. Other exceptions may break your application.

In your bootstrap file (index.php) you have your controller front setup:

<?php
/**
* File: index.php
*/

require_once 'Zend/Controller/Front.php';

/**
* Setup controller
*/
$controller = Zend_Controller_Front::getInstance();
$controller->setControllerDirectory( '../application/controllers');
$controller->dispatch();

For using the ErrorHandler plugin, you need to have an error controller and an error view.

Here is an example of a simple errorcontroller script, that uses a log to write exceptions.

<?php
/**
* ErrorController - The default error controller class
*
* File: application/controllers/ErrorController.php
*
*/

require_once 'Zend/Controller/Action.php' ;
require_once 'Zend/Log.php';
require_once 'Zend/Log/Writer/Stream.php';

class ErrorController extends Zend_Controller_Action
{

    /**
     * This action handles
     *    - Application errors
     *    - Errors in the controller chain arising from missing
     *     controller classes and/or action methods
     */
    public function errorAction ()
    {
        $content = null;
        $errors = $this->_getParam ('error_handler') ;
        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER :
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION :
                // 404 error -- controller or action not found
                $this->getResponse ()->setRawHeader ( 'HTTP/1.1 404 Not Found' ) ;
                // ... get some output to display...
                $content .= "<h1>404 Page not found!</h1>" . PHP_EOL;
                $content .= "<p>The page you requested was not found.</p>";
                break ;
            default :
                // application error; display error page, but don't change            
                // status code
                $content .= "<h1>Error!</h1>" . PHP_EOL;
                $content .= "<p>An unexpected error occurred with your request. Please try again later.</p>";
                // ...

                // Log the exception
                $exception = $errors->exception;
                $log = new Zend_Log(
                    new Zend_Log_Writer_Stream('/path/to/logs/demo-exceptions_log' )
                );
                $log->debug(
                 $exception->getMessage() . PHP_EOL . $exception->getTraceAsString()
                );
                break ;
        }

        // Clear previous content
        $this->getResponse()->clearBody();
        $this->view->content = $content;
    }
}

A minimalistic error view file resides in /application/views/scripts/error/error.phtml using Zend Framework standards.

<html>
    <head>
     <title>An error has occured</title>
    </head>
    <body>
            <?php echo $this->content; ?>
    </body>
</html>

2. Catching Exceptions

If we want to catch all kinds of exceptions, we better enable our MVC model to throw exceptions.

<?php
/**
* File: index.php
*/

require_once 'Zend/Controller/Front.php';
require_once 'Zend/Log.php';
require_once 'Zend/Log/Writer/Stream.php'

/**
* Setup controller
*/
$controller = Zend_Controller_Front::getInstance();
$controller->setControllerDirectory( '../application/controllers');
$controller->throwExceptions( true);

try {
    $controller->dispatch();
} catch (Exception $e) {
    // Handle the exception
    $log = new Zend_Log(
        new Zend_Log_Writer_Stream('/path/to/logs/demo-exceptions_log' )
    );
    $log->debug(
        $e->getMessage() . PHP_EOL . $e->getTraceAsString()
    );
}

Another way to handle exceptions, is the use of the response object.

<?php
/**
* File: index.php
*/

require_once 'Zend/Controller/Front.php';
require_once 'Zend/Log.php';
require_once 'Zend/Log/Writer/Stream.php'

/**
* Setup controller
*/
$controller = Zend_Controller_Front::getInstance();
$controller->setControllerDirectory( '../application/controllers');
$controller->returnResponse( true);

$response = $controller ->dispatch();
if ($response ->isException()) {
    $exceptions = $response->getException();
    $log = new Zend_Log(
        new Zend_Log_Writer_Stream('/path/to/logs/demo-exceptions_log' )
    );
    $log->debug(
        $exceptions->getMessage() . PHP_EOL . $exceptions->getTraceAsString()
    );
    // Handle the exception
} else {
    $response->sendHeaders();
    $response->outputBody();
}

Now I'm actually stuck, because I want to capture these exceptions in a logfile, but I still want to use the ErrorHandler functionality. This is I want a 404 page when a controller, action or module is not found, a 500 page for exceptions thrown within the application and all the rest working as it is supposed to be.

Thursday, November 08, 2007

Hunting for professional php developers

These days php is "hot" and everyone wants a piece of php. The only problem is that there aren't many "Certified Zend Php Developers" or ZCE's out there.

When I look at the Belgian Zend Yellow Pages, only 24 (today's count) certified php developers are out there, but by pure guesswork I estimate there's a need of at least 100 certified engineers.

Where can you find them ? And how can you persuade them into getting certified ? I'm not a recruiter, but I know lot's of people who are ready to hire them instantly.

I already got my certifications (php 4 and php 5) and it feels good to be part of an elite but small group of professional php developers. And let's be honest, who doesn't want to receive credits for their work ?!?

If you want to know more about this certification path, I can lay it out for you quite simple (just repeating Zend Certification php page):
If you wonder if you can pass the exam, Zend has also an example exam ready for you.

For further questions, feel free to contact me or any other ZCE mentioned on the Yellow Pages for PHP Professionals.

Good luck and maybe we'll be working together...

Added: I just found out that International Php Magazine has posted a message for joining up professional php developers over at phpclasses.com.

Monday, November 05, 2007

Google's OpenSocial

Today everyone talks about OpenSocial, a recent service Google launches to interact with social networks and maintaining links with friends. The idea is that everyone can create their own applications (or widgets) that can link to whatever service that's out there using REST or core Google API's (e.g. with Orkut).

The idea behind this service is the popularity of Facebook's API that enables users to create custom applications on the Facebook core. And as a result, many other social sites have released their API's to their users for extra valued user experiences.

According to the OpenSocial FAQ's, this API is capable to communicate with already existing services using REST and JavaScript and can be used on .NET, Java and PHP environments.
Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 License.