Zend Framework Source Code Snippets

Zend Bootstrap

Bookmark and Share
1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
38
39
4041
42
43
44
4546
47
48
49
5051
52
53
54
5556
57
58
59
6061
62
63
64
6566
67
68
69
7071
72
73
74
7576
77
78
79
8081
82
83
84
8586
87
88
89
9091
92
93
94
9596
97
98
99
100101
102
103
104
105106
107
108
109
110111
112
113
114
115116
117
118
119
120121
122
123
124
125126
127
128
129
130131
132
133
134
135136
137
138
139
140141
142
143
144
145146
147
148
149
150151
152
153
154
155156
157
158
159
160161
162
163
164
165166
167
168
169
170171
172
173
174
175176
177
178
179
180181
182
183
184
185186
187
188
189
190191
192
193
194
195196
197
198
199
200201
202
203
204
205206
207
208
209
210211
212
213
214
215216
217
218
219
220221
222
223
224
225226
227
228
229
230231
232
233
234
235236
237
238
239
240241
242
243
244
245246
<?php
 
function __autoload($className) {
    require $className = str_replace('_', '/', $className) . '.php';
} 
class Bootstrap{
 
    public static $frontController = null;
     public static $root = '';
 
    public static $registry = null;
 
    public static function run(){        self::prepare();
 
        $response = self::$frontController->dispatch();
        self::sendResponse($response);
    } 
 
    public static function prepare(){
        self::setupEnvironment();
         self::setupRegistry();
        self::setupConfiguration();
 
        self::setupFrontController();
        self::setupErrorHandler(); 
        self::setupController();
        self::setupView();
        self::setupDatabase();
        self::setupSessions();        self::setupTranslation();
        self::setupRoutes();
        self::setupAcl();
        self::setupDebug();
    } 
 
 
    public static function setupEnvironment(){
        error_reporting(E_ALL ^ E_NOTICE);        ini_set('display_errors', true);
 
        date_default_timezone_set('Europe/Bucharest');
 
        self::$root = dirname(dirname(__FILE__)); 
        $configType = (isset($_SERVER['SERVER_NAME']) && ($_SERVER['SERVER_NAME'] == '127.0.0.1' OR $_SERVER['SERVER_NAME'] == 'localhost')) ? 'development' : 'production';
        define('APPLICATION_ENVIRONMENT', $configType);
 
        define('HTMLPURIFIER_PREFIX', self::$root . '/library');    }
 
 
    public static function setupRegistry() {
        self::$registry = new Zend_Registry(array(), ArrayObject::ARRAY_AS_PROPS);        Zend_Registry::setInstance(self::$registry);
    }
 
    public static function setupConfiguration() {
         $config = new Zend_Config_Ini(
            self::$root . '/application/config/main.ini',
            APPLICATION_ENVIRONMENT
        );
         self::$registry->configuration = $config;
 
        //save $siteRootDir in registry:
        self::$registry->set('siteRootDir', self::$root );
        self::$registry->set('applicationRootDir', self::$root . '/application' ); 
        self::$registry->set('siteUploadDir', self::$root . '/uploads');
 
        self::$registry->set('siteRootUrl', 'http://' . $_SERVER['HTTP_HOST'] );
        self::$registry->set('siteUploadUrl', '/uploads' );    }
 
 
    public static function setupFrontController(){
        self::$frontController = Zend_Controller_Front::getInstance();        self::$frontController->throwExceptions(true);
        self::$frontController->returnResponse(true);
 
        self::$frontController->addModuleDirectory(self::$root . '/application/modules');
         self::$frontController->setParam('registry', self::$registry);
 
        self::$frontController->setParam('env', APPLICATION_ENVIRONMENT);
 
         $response = new Zend_Controller_Response_Http; // Set default Content-Type
        $response->setHeader('Content-Type', 'text/html; charset=UTF-8', true);
        self::$frontController->setResponse($response);
    }
  
    public static function setupErrorHandler() {
        self::$frontController->throwExceptions(false);
 
        self::$frontController->registerPlugin(new Zend_Controller_Plugin_ErrorHandler(            array(
                'module'     => 'default',
                'controller' => 'error',
                'action'     => 'error')
            )); 
        $writer = new Zend_Log_Writer_Firebug();
        $logger = new Zend_Log($writer);
        Zend_Registry::set('logger',$logger);
  
    }
 
 
    public static function setupController(){        Zend_Controller_Action_HelperBroker::addHelper(new GSD_Controller_Action_Helper_AuthUsers());
        Zend_Controller_Action_HelperBroker::addHelper(new GSD_Controller_Action_Helper_Breadcrumbs());
    }
 
    public static function setupView() { 
        $view = new Zend_View(array('encoding'=>'UTF-8'));
        $view->addHelperPath('GSD/View/Helper', 'GSD_View_Helper_');
 
        $viewRendered = new Zend_Controller_Action_Helper_ViewRenderer($view);        Zend_Controller_Action_HelperBroker::addHelper($viewRendered);
 
        Zend_Layout::startMvc(
            array(
                'layoutPath' => self::$root . '/application/layouts',                'layout' => 'default'
            )
        );
 
        if (self::$frontController) {            self::$frontController->registerPlugin(new GSD_Layout_Controller_Plugin_Layout());
        }
    }
 
     public static function sendResponse(Zend_Controller_Response_Http $response){
        $response->sendResponse();
    }
 
     public static function setupDatabase($options = array()){
        extract($options);
 
        $config = self::$registry->configuration;
         $db = Zend_Db::factory($config->db->adapter, $config->db->toArray());
 
        $profiler = new Zend_Db_Profiler_Firebug('All DB Queries');
        $profiler->setEnabled(true);
        $db->setProfiler($profiler); 
        $db->query("SET NAMES 'utf8'");
 
        self::$registry->database = $db;
        Zend_Db_Table::setDefaultAdapter($db); 
        if (!isset($dissableCache) && $dissableCache !== true) {
            $frontendOptions = array(
                'automatic_serialization' => true
                ); 
 
                $backendOptions  = array(
                    'cache_dir' => self::$root . '/data/cache/db_table'
                ); 
            $cache = Zend_Cache::factory('Core',
                                         'File',
                                         $frontendOptions,
                                         $backendOptions); 
 
            // Next, set the cache to be used with all table objects
            Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);
        }    }
 
 
    public static function setupSessions(){
        if (isset($_POST["PHPSESSID"])) {            session_id($_POST["PHPSESSID"]);
        }
 
        // Now set session save handler to our custom class which saves the data in MySQL database
        $sessionManager = new GSD_Session_Manager();        Zend_Session::setOptions(array(
            'gc_probability' => 1,
            'gc_divisor' => 5000
            ));
        Zend_Session::setSaveHandler($sessionManager); 
        $defSession = new Zend_Session_Namespace('Main', true);
        Zend_Registry::set('defSession', $defSession);
    }
  
    public static function setupTranslation(){
        $options = array(
                    'scan' => Zend_Translate::LOCALE_FILENAME,
                    'disableNotices' => true,                    );
        $translate = new Zend_Translate('gettext', Zend_Registry::get('siteRootDir') . '/application/languages/', 'auto', $options);
        Zend_Registry::set('Zend_Translate', $translate);
 
    } 
 
    public static function setupRoutes(){
        // define some routes (URLs)
        $router = self::$frontController->getRouter(); 
        $config = new Zend_Config_Ini(
            self::$root . '/application/config/routes.ini',
            'development'
        ); 
        $router->addConfig($config, 'routes');
    }
 
     public static function setupAcl(){
        self::$frontController->registerPlugin(new GSD_Controller_Plugin_Acl());
    }
 
    public static function setupDebug() {        $scBar = new Scienta_Controller_Plugin_Debug(array(
           'database_adapter' =>  self::$registry->database, // or array of adapters
           'memory_usage' =>      TRUE, // default value shown
           'collect_view_vars' => TRUE,
           'sort_view_vars' =>    TRUE,           'show_exceptions' =>   TRUE,
           'handle_errors' =>     FALSE
        ));
        self::$frontController->registerPlugin($scBar);
    }}

Comments

Themodem Themodem
1 year ago

The origional script is from the following blog

http://blog.astrumfutura.com/

I also use the origional bootstrap file as ive found it to be the best out there

davedevelopment davedevelopment
1 year ago

I've used Maugrim the Reapers a few times, but I've started using a simpler one from the quick start guide now.

Akrabat's latest post is worth a read http://akrabat.com/2009/03/25/initial-notes-on-zend_application/

iongion iongion
1 year ago

Are you sure YOU came up with this boostrap structure ? Wasn't there a download link on zftalk ? circuss ...

You must login before commenting on a snippet. If you do not have an account, please register.

Snippet description

After starting working with zend framework i found all sorts of examples of bootstrap files, but a lot of them seem pretty messy to me since all the calls to zend components were basically thrown in there.

So after a lot of looking around i came up with a bootstrap files that is more to my liking. I found the initial class on a blog post when i was looking around but i don't remember where, so sorry for not giving it the credit.

As you can see basicly i just grouped toghether similar comands and make it all look much more nicer and cleaner. And also i added the autoload function since i really think this is a much faster way then the Zend_Loader option. As for what is run, lets take it one by one:
function run
This is the main function that calls the prepare function and starts up the whole Zend Framework.

function prepare
Calls all the internal methods that setup the framework to start dispatching the request.

function setupEnvironment
Here i added the error reporting options and also i define some constants like configuration type ( development - production )

function setupRegistry()
Start the Zend Registry.

function setupConfiguration
Get the config file ( contains the db conection data etc. ) and save the configuration in Zend_Registry

function setupFrontController
Starts the front controller and setup the modular aproach.

function setupErrorHandler
Registers the Error handler plugins and logger.

function setupController
Here is the place to put your Controll Action Helpers

function setupView
start the Zend_View and MVC structure, add the custom HelperPath

function setupDatabase
start your db connection bassed on the configuration we stored in the registry. Also started the Zend_Db_Table cache system.

function setupSessions
Start you session, i used a custom Session Manager that uses a mysql database as storage.

And that is about it. I skipped some of them because i thought they were pretty obvious.

Hope you will find this usefully, and await your comments.

Snippet details

Created:
gabriel solomon gabriel solomon
1 year ago
Edited:
gabriel solomon gabriel solomon
1 year ago
Revision Id:
88
Edit Message:
Initial Release
Tags:
bootstrap
Comments:
3
Views:
1752
Points:
0 (2 votes)

History

r88

Initial Release

gabriel solomon gabriel solomon
1 year ago