The ultimate CakePHP bootstrap technique
Posted by Felix Geisendörfer, on Aug 15, 2006 - in PHP & CakePHP » Core & Hacking
Ok, I shouldn't use such a buzz-headline, but I was very happy today, when I discovered a new way to bootsrap CakePHP wihout having to render a page. This is especially useful when you try to embed CakePHP in existing php apps (drupal, wordpress, ..., ?), or when you try to write unit tests for highly coupled classes such as Controllers or Models.
The idea is very simple, and I felt sort of stupid that I didn't see it earlier. When you look in your app/webroot/index.php file there are the following lines at the end:
-
} else {
-
$Dispatcher=new Dispatcher();
-
$Dispatcher->dispatch($url);
-
}
Their only purpose is to intialize an instance of the Dispatcher class and to request a Controller action for our $url. But what it also does, is to check weather or not the $_GET['url'] variable contains the value "favicon.ico" in which case *no dispatching* is happening. Now this gives us an easy way for including the webroot/index.php file without automatically rendering a page:
-
$_GET['url'] = 'favicon.ico';
-
require_once('path_to_app_dir'.DIRECTORY_SEPARATOR.'webroot'.DIRECTORY_SEPARATOR.'index.php');
Now we can easily create instances of single controllers, models, etc. or use the Dispatcher to render a page. The only thing we might need to do is call loadController(null) for loading the AppController (or others) and calling loadModels() to load our model files.
--Felix Geisendörfer aka the_undefined