LifecycleCallbackTest.php 2.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?php

namespace Doctrine\Tests\ORM\Functional;

require_once __DIR__ . '/../../TestInit.php';

class LifecycleCallbackTest extends \Doctrine\Tests\OrmFunctionalTestCase
{
    protected function setUp() {
        parent::setUp();
        try {
            $this->_schemaTool->createSchema(array(
                $this->_em->getClassMetadata('Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity')
            ));
        } catch (\Exception $e) {
            // Swallow all exceptions. We do not test the schema tool here.
        }
    }
    
    public function testPreSavePostSaveCallbacksAreInvoked()
    {        
        $entity = new LifecycleCallbackTestEntity;
        $entity->value = 'hello';
romanb's avatar
romanb committed
24
        $this->_em->persist($entity);
25 26
        $this->_em->flush();
        
romanb's avatar
romanb committed
27 28
        $this->assertTrue($entity->prePersistCallbackInvoked);
        $this->assertTrue($entity->postPersistCallbackInvoked);
29 30 31 32
        
        $this->_em->clear();
        
        $query = $this->_em->createQuery("select e from Doctrine\Tests\ORM\Functional\LifecycleCallbackTestEntity e");
33
        $result = $query->getResult();
34 35 36 37 38 39 40 41 42 43 44 45
        $this->assertTrue($result[0]->postLoadCallbackInvoked);
        
        $result[0]->value = 'hello again';
        
        $this->_em->flush();
        
        $this->assertEquals('changed from preUpdate callback!', $result[0]->value);
    }
}

/**
 * @Entity
46
 * @HasLifecycleCallbacks
47
 * @Table(name="lc_cb_test_entity")
48 49 50 51
 */
class LifecycleCallbackTestEntity
{
    /* test stuff */
romanb's avatar
romanb committed
52 53
    public $prePersistCallbackInvoked = false;
    public $postPersistCallbackInvoked = false;
54 55 56 57 58 59 60 61 62 63 64 65
    public $postLoadCallbackInvoked = false;
    
    /**
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     * @Column(type="string", length=255)
     */
    public $value;
    
romanb's avatar
romanb committed
66 67 68
    /** @PrePersist */
    public function doStuffOnPrePersist() {
        $this->prePersistCallbackInvoked = true;
69 70
    }
    
romanb's avatar
romanb committed
71 72 73
    /** @PostPersist */
    public function doStuffOnPostPersist() {
        $this->postPersistCallbackInvoked = true;
74 75 76 77 78 79 80 81 82 83 84
    }
    
    /** @PostLoad */
    public function doStuffOnPostLoad() {
        $this->postLoadCallbackInvoked = true;
    }
    
    /** @PreUpdate */
    public function doStuffOnPreUpdate() {
        $this->value = 'changed from preUpdate callback!';
    }
85
}