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 22: Ev<strong>en</strong>t List<strong>en</strong>ers 309<br />

Chapter 22<br />

Ev<strong>en</strong>t List<strong>en</strong>ers<br />

Introduction<br />

<strong>Doctrine</strong> provides flexible ev<strong>en</strong>t list<strong>en</strong>er architecture that not only allows list<strong>en</strong>ing for<br />

differ<strong>en</strong>t ev<strong>en</strong>ts but also for altering the execution of the list<strong>en</strong>ed methods.<br />

There are several differ<strong>en</strong>t list<strong>en</strong>ers and hooks for various <strong>Doctrine</strong> compon<strong>en</strong>ts. List<strong>en</strong>ers<br />

are separate classes whereas hooks are empty template methods within the list<strong>en</strong>ed class.<br />

Hooks are simpler than ev<strong>en</strong>t list<strong>en</strong>ers but they lack the separation of differ<strong>en</strong>t aspects. An<br />

example of using <strong>Doctrine</strong>_Record hooks:<br />

// models/BlogPost.php<br />

Listing<br />

22-1<br />

class BlogPost ext<strong>en</strong>ds <strong>Doctrine</strong>_Record<br />

{<br />

// ...<br />

public function preInsert($ev<strong>en</strong>t)<br />

{<br />

$invoker = $ev<strong>en</strong>t->getInvoker();<br />

}<br />

}<br />

$invoker->created = date('Y-m-d', time());<br />

By now we have defined lots of models so you should be able to define your own<br />

setTableDefinition() for the BlogPost model or ev<strong>en</strong> create your own custom model!<br />

Now you can use the above model with the following code assuming we added a title, body<br />

and created column to the model:<br />

// test.php<br />

Listing<br />

22-2<br />

// ...<br />

$blog = new BlogPost();<br />

$blog->title = 'New title';<br />

$blog->body = 'Some cont<strong>en</strong>t';<br />

$blog->save();<br />

echo $blog->created;<br />

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

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

Saved successfully!

Ooh no, something went wrong!