Custom Mapper

You can alter any of the command(s) generated by the ORM mappers by replacing it with your own implementation. Another option is to create your own commands and link them to the update, insert or delete.

Hook into Insert/User/Delete command

To add your own handler when an entity is created, updated or deleted modify the methods queueCreate, queueUpdate and queueDelete of your entity wrapper.

class MyMapper extends Mapper
{
    public function queueCreate($entity, Node $node, State $state): ContextCarrierInterface
    {
        $cmd = parent::queueCreate($entity, $node, $state);
        return $cmd;
    }

    public function queueUpdate($entity, Node $node, State $state): ContextCarrierInterface
    {
        $cmd = parent::queueUpdate($entity, $node, $state);
        return $cmd;
    }

And assign the entity to the specific mapper:

/**
 * @Entity(mapper="MyMapper")
 */
class User
{
   //...
}

Command Chain

We can link another command to be executed right after $cmd:

public function queueCreate($entity, Node $node, State $state): ContextCarrierInterface
{
    $cmd = parent::queueCreate($entity, $node, $state);

    $cs = new ContextSequence();
    $cs->addPrimary($cmd);
    $cs->addCommand(new OurCommand());

    return $cs;
}

In case of Create, the primary key sequence won't be available at the moment of queueCreate call (it will be available after SQL INSERT query).

This value must be forwarded to our command using forward method from $cmd:

public function queueCreate($entity, Node $node, State $state): ContextCarrierInterface
{
    $cmd = parent::queueCreate($entity, $node, $state);
    $our = new OurCommand();

    // wait for cmd_id value or fail
    $our->waitContext('cmd_id', true);

    // send lastID value as cmd_id to $our command
    $cmd->forward(Insert::INSERT_ID, $our, 'cmd_id');

    $cs = new ContextSequence();
    $cs->addPrimary($cmd);
    $cs->addCommand($our);

    return $cs;
}

Example: see sample implementation which copies all entity changes into a separate table.

Autoconfiguration

ORM schema provides one reserved Entity constant SCHEMA which can be used to specify custom Mapper behavior. You can combine schema-builder and custom mapper implementation to create configurable mappers.

Cycle does not provide such mapper implementations (a.k.a. "behaviors") out of the box, feel free to suggest your implementation as an extension.

Edit this page