Cobby
Cobby

Reputation: 5454

Acceptable entity logic?

I have two entities, Post and Post\Version. I've set it up so the versioning is automatically handled within the Post entity, so the developer doesn't have to use Post\Version manually. It doesn't use the EntityManager, just a bit of reflection... is this ok?

<?php

public function setContent($content)
{
    $this->_setVersionValue('content', $content);
}

private function _setVersionValue($property, $value)
{
    // get reflection property
    $version = clone $this->getActiveVersion();
    $refl = new \ReflectionProperty($version, $property);
    $refl->setAccessible(true);

    // update value
    $version->setCreatedBy($this->getCurrentUser());
    $refl->setValue($version, $value);

    // clear ID
    $reflProp = new \ReflectionProperty($version, 'id');
    $reflProp->setAccessible(true);
    $reflProp->setValue($version, null);

    // set to new version
    $this->setActiveVersion($version);
}

The Post only stores a reference to the latest version. Version's have a back-reference to the Post they are belong.

Upvotes: 0

Views: 492

Answers (2)

Crozin
Crozin

Reputation: 44376

I suppose A re-usable Versionable Behavior for Doctrine2 from official blog is a way easier in final usage. Also it's easier to adapt to other entities.

PS. Both Post and PostVersion should be in the same namespace (eg. MyProject\Entity\Blog)

Upvotes: 1

beberlei
beberlei

Reputation: 4337

This is perfectly fine. Of course you should always find your own workflow of how to mix up classes and instances.

Upvotes: 0

Related Questions