10.04.2018 Views

Doctrine_manual-1-2-en

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 16: Behaviors 262<br />

actAs: [SoftDelete]<br />

columns:<br />

name:<br />

type: string(255)<br />

primary: true<br />

Lets check the SQL that is g<strong>en</strong>erated by the above models:<br />

Listing<br />

16-69<br />

// test.php<br />

Listing<br />

16-70<br />

// ...<br />

$sql = <strong>Doctrine</strong>_Core::g<strong>en</strong>erateSqlFromArray(array('SoftDeleteTest'));<br />

echo $sql[0];<br />

The above code would output the following SQL query:<br />

CREATE TABLE soft_delete_test (name VARCHAR(255),<br />

deleted TINYINT(1) DEFAULT '0' NOT NULL,<br />

PRIMARY KEY(name)) ENGINE = INNODB<br />

Now lets put the behavior in action.<br />

You are required to <strong>en</strong>able DQL callbacks in order for all executed queries to have the dql<br />

callbacks executed on them. In the SoftDelete behavior they are used to filter the select<br />

statem<strong>en</strong>ts to exclude all records where the deleted flag is set with an additional WHERE<br />

condition.<br />

Enable DQL Callbacks<br />

Listing<br />

16-71<br />

// bootstrap.php<br />

// ...<br />

$manager->setAttribute(<strong>Doctrine</strong>_Core::ATTR_USE_DQL_CALLBACKS, true);<br />

Now save a new record so we can test the SoftDelete functionality:<br />

Listing<br />

16-72<br />

// test.php<br />

// ...<br />

$record = new SoftDeleteTest();<br />

$record->name = 'new record';<br />

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

Now wh<strong>en</strong> we call delete() the deleted flag will be set to true:<br />

Listing<br />

16-73<br />

// test.php<br />

Listing<br />

16-74<br />

// ...<br />

$record->delete();<br />

print_r($record->toArray());<br />

The above example would produce the following output:<br />

$ php test.php<br />

Array<br />

(<br />

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

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

Saved successfully!

Ooh no, something went wrong!