10.04.2018 Views

Doctrine_manual-1-2-en

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 2: Getting Started 22<br />

Listing<br />

2-20<br />

// bootstrap.php<br />

/**<br />

* Bootstrap <strong>Doctrine</strong>.php, register autoloader specify<br />

* configuration attributes and load models.<br />

*/<br />

require_once(dirname(__FILE__) . '/lib/v<strong>en</strong>dor/doctrine/<strong>Doctrine</strong>.php');<br />

Register Autoloader<br />

Now that we have the <strong>Doctrine</strong> class pres<strong>en</strong>t, we need to register the class autoloader<br />

function in the bootstrap file:<br />

Listing<br />

2-21<br />

// bootstrap.php<br />

// ...<br />

spl_autoload_register(array('<strong>Doctrine</strong>', 'autoload'));<br />

Lets also create the singleton <strong>Doctrine</strong>_Manager instance and assign it to a variable named<br />

$manager:<br />

Listing<br />

2-22<br />

// bootstrap.php<br />

// ...<br />

$manager = <strong>Doctrine</strong>_Manager::getInstance();<br />

Autoloading Explained<br />

You can read about the PHP autoloading on the php website 17 . Using the autoloader allows<br />

us to lazily load classes as they are requested instead of pre-loading all classes. This is a<br />

huge b<strong>en</strong>efit to performance.<br />

The way the <strong>Doctrine</strong> autoloader works is simple. Because our class names and paths are<br />

related, we can determine the path to a <strong>Doctrine</strong> class based on its name.<br />

Imagine we have a class named <strong>Doctrine</strong>_Some_Class and we instantiate an instance of it:<br />

Listing<br />

2-23<br />

$class = new <strong>Doctrine</strong>_Some_Class();<br />

The above code will trigger a call to the <strong>Doctrine</strong>_Core::autoload() function and pass it<br />

the name of the class instantiated. The class name string is manipulated and transformed in<br />

to a path and required. Below is some pseudo code that shows how the class is found and<br />

required:<br />

Listing<br />

2-24<br />

class <strong>Doctrine</strong><br />

{<br />

public function autoload($className)<br />

{<br />

$classPath = str_replace('_', '/', $className) . '.php';<br />

$path = '/path/to/doctrine/' . $classPath;<br />

require_once($path);<br />

return true;<br />

}<br />

}<br />

17. http://www.php.net/spl_autoload_register<br />

----------------- Brought to you by

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!