Zend Framework Bootstrap

Bootstrap is a setup process of different framework component to make easily accessible/available in application. It is very important to setup all require component of framework, so whenever it can be used effectively without any hassle. Bootstrap file is very important file for project using Zend Framework. Bootstrap file or bootstrap process is not a standard in Zend Framework, but to create bootstrap file but it is good practice. Many people use it many way.

It is important to know what are the component of Zend Framework is require. Following is good example of bootstrap.php


require_once 'Zend/Loader.php';

class Bootstrap
{

    public static $frontController = null;

    public static $root = '';

    public static $registry = null;

    //Primary function will be called first from index.php, it will call rest of functions to boot
	public static function run()
    {
        self::prepare();
        $response = self::$frontController->dispatch();
        self::sendResponse($response);
    }

    /*It is used to prepare from macro view.
	It gives macro view idea about preparation.
	Sequence of each call is important.
	*/
	public static function prepare()
    {
        self::setupPath();
    	self::setupErrorReporting();

		//To load all classes automatically, without include or require statement
        Zend_Loader::registerAutoload();

        self::setupRegistry();
        self::setupConfiguration();
        self::setupFrontController();
        self::setupView();
		self::setupLogger();
        self::setupDatabase();
		self::setupSession();
    }

    //Error reporting setting
	public static function setupErrorReporting()
    {
    	error_reporting(E_ALL|E_STRICT);
    	ini_set('display_errors', true);
    }

    //Path settings will be done using this
	public static function setupPath()
    {
        $root = dirname(dirname(__FILE__));
		set_include_path(
		    $root . '/library' . PATH_SEPARATOR .
			$root . '/application' . PATH_SEPARATOR .
			$root . '/application/models' . PATH_SEPARATOR .
			 get_include_path()
		);
        self::$root = dirname(dirname(__FILE__));
    }

	//Date time setting will be done here
	public static function setupDateTime()
	{
		date_default_timezone_set('Europe/London');
	}

    //Registry setting will be done here.
	public static function setupRegistry()
    {
        self::$registry = new Zend_Registry(array(), ArrayObject::ARRAY_AS_PROPS);
        Zend_Registry::setInstance(self::$registry);
    }

    //Configuration file reading & setting up configuration will be done using following.
	public static function setupConfiguration()
    {
        $config = new Zend_Config_Ini(
            self::$root . '/application/config/config.ini',
            'general'
        );
        self::$registry->configuration = $config;
    }

    //Important: Setting of front controller will done here.
	public static function setupFrontController()
    {
        self::$frontController = Zend_Controller_Front::getInstance();
        self::$frontController->throwExceptions(true);
        self::$frontController->returnResponse(true);
        self::$frontController->setControllerDirectory(
            array(
                'default' => self::$root . '/application/controllers',
				'admin' => self::$root . '/application/admin/controllers'
            )
        );
        self::$frontController->setParam('registry', self::$registry);
    }

    /*View setup will be done here.
	Setup view encoding, layout setup also done here
	*/
	public static function setupView()
    {
        $view = new Zend_View;
        $view->setEncoding('UTF-8');
        $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer($view);
        Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
        Zend_Layout::startMvc(
            array(
                'layoutPath' => self::$root . '/application/views/layouts',
                'layout' => 'common',
                'pluginClass' => 'ZFBlog_Layout_Controller_Plugin_Layout'
            )
        );
    }

    /*DB setup done here.
	Read configuration, create db instance & set in registry to use in other part of application.*/
	public static function setupDatabase()
    {
        $config = self::$registry->configuration;
        $db = Zend_Db::factory($config->db->adapter, $config->db->toArray());
        $db->query("SET NAMES 'utf8'");
        self::$registry->database = $db;
        Zend_Db_Table::setDefaultAdapter($db);
    }

    //Response will be sent from following function, also set header for response.
	public static function sendResponse(Zend_Controller_Response_Http $response)
    {
        $response->setHeader('Content-Type', 'text/html; charset=UTF-8', true);
    	$response->sendResponse();
    }

	//Logger setup will can be done using following
	public static function setupLogger()
	{
		/**
		* Create a log formatter
		*/
		$format = '%timestamp% %priorityName% (%priority%): %message%' . PHP_EOL;
		$formatter = new Zend_Log_Formatter_Simple($format);

		/**
		* Create a file logger
		*/
		$stream = @fopen(APP_DIR . "tmp/logs/" . date("Y-m-d") . ".php", 'a', false);
		if (!$stream)
		{
			throw new Exception('Failed to open stream');
		}
		try
		{
			$fileWriter = new Zend_Log_Writer_Stream($stream);
			$fileWriter->setFormatter($formatter);
			$fileLogger = new Zend_Log($fileWriter);
			Zend_Registry::set("fileLogger", $fileLogger);
		}
		catch (Zend_Log_Exception $e)
		{
			echo "Error: " . $e->getMessage();
		}
		catch (Zend_Exception $e)
		{
			echo "Error: " . $e->getMessage();
		}
	}

	/*
	Zend session setting done here.
	*/
	public static function setupSession()
	{
		try
		{
			Zend_Session::setOptions(array(
				'save_path' => APP_DIR . "/tmp/sessions",
				'remember_me_seconds' => 7200,
		));
		Zend_Session::start();
		}
		catch (Zend_Session_Exception $e)
		{
			$dbLogger->log('Error: ' . $e->getMessage(), 1);
			$fileLogger->log($e->getMessage(), 1);
		}
		$defaultNs = new Zend_Session_Namespace('default');

		Zend_Registry::set("defaultNs", $defaultNs);

		if($config->log_level == 2)
		{
			$fileLogger->info("Sessions setup finished!");
		}
	}

}

To run this bootstrap file we just need to add following code to index.php

require '../application/Bootstrap.php';
Bootstrap::run();

There are many Zend Framework component that is used in normal/regular/usual project but I have not placed it in above code listing. Please suggest.

Please feel free to provide your feedback.

Advertisements

12 thoughts on “Zend Framework Bootstrap

  1. I found your site on technorati and read a few of your other posts. Keep up the good work. I just added your RSS feed to my Google News Reader. Looking forward to reading more from you down the road!

  2. I don’t really see how this is useful… What you’ve got here is a class where every method is static, and all methods seem to be simply run in order. How does this differ, other than structurally, from simply including a file which contains the content of each of your static methods in order?

    This class doesn’t seem to provide any value other than organizing each portion of the bootstrapping process into a semantically useful static method name.

    Sorry to sound so negative — I don’t mean to be mean or anything, I just though I’d put in my two cents, since it’s a blog ‘n all.

  3. hi,

    why don’t you use a plugin ?

    e.g.:
    – index.php
    require ‘../application/bootstrap.php’;

    – bootstrap.php
    // put library in include_path
    // registerAutoload
    // Zend_Controller_Front::getInstance()
    // registerPlugin(new InitPlugin)
    // default module
    // dispatch

    – InitPlugin
    // optionnal __construct to set private attributes
    // routeStartup to call methods like you did in prepare method
    // some methods to do the job

    this solution, in my opinion, respects more the ZF way of coding

  4. Pingback: JohnPuPu » Blog Archive » links for 2008-12-07

  5. Hi,

    It might interest you to know that for ZF 1.8 we will be formalizing the Application and Bootstrap code.

    Here is the formal proposal:

    http://framework.zend.com/wiki/display/ZFPROP/Zend_Application+-+Ben+Scholzen

    and here is some notes we’d been gathering:

    http://framework.zend.com/wiki/display/~matthew/Zend_Application+Requirements

    So, as you can see, we are definitely thinking about all of the problems you’d been solving too. If you have any input for our requirements, please add them!

    Ralph

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s