workflower icon indicating copy to clipboard operation
workflower copied to clipboard

Sample code

Open abdfork opened this issue 8 years ago • 1 comments

Is there any sample code creating a ProcessContext, Events, and starting the workflow?

abdfork avatar Dec 14 '16 16:12 abdfork

If you directly use Workflower and PHPMentorsWorkflowerBundle, a code for starting processes of a workflow would be as the following:

// ...

class LoanRequestProcessStartUsecase implements CommandUsecaseInterface, ProcessAwareInterface
{
    // ...

    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    /**
     * @var Process
     */
    private $process;

    // ...

    /**
     * {@inheritdoc}
     */
    public function setProcess(Process $process)
    {
        $this->process = $process;
    }

    /**
     * {@inheritdoc}
     *
     * @return void
     */
    public function run(EntityInterface $entity)
    {
        assert($entity instanceof EventContextInterface);
        assert($entity->getProcessContext() instanceof LoanRequestProcess);

        $this->process->start($entity);

        // ...
        $loanRequestProcess = $entity->getProcessContext(); /* @var $loanRequestProcess LoanRequestProcess */
        $loanRequestProcess->setCurrentTask($loanRequestProcess->getWorkflow()->getCurrentFlowObject()->getId()); // set some information for query

        $this->entityManager->beginTransaction();
        try {
            $this->loanRequestProcessRepository->add($loanRequestProcess);
            $this->entityManager->flush();
            $this->entityManager->commit();
        } catch (\Exception $e) {
            $this->entityManager->rollback();
            throw $e;
        }
    }
}

In these cases, the usecase object would be called from controllers, CLI commands, and event listeners as the following:

// ...

class LoanRequestProcessListener
{
    // ...

    /**
     * @var LoanRequestProcessStartUsecase
     */
    private $loanRequestProcessStartUsecase;

    // ...

    /**
     * @param LoanRequestApplicationEvent $event
     */
    public function onSuccess(LoanRequestApplicationEvent $event)
    {
        try {
            $this->loanRequestProcessStartUsecase->run(new EventContext('Start', new LoanRequestProcess($event->getLoanRequestApplication()));
        } catch (\Exception $e) {
            // ...
        }

        // ...
    }
}

iteman avatar Dec 15 '16 03:12 iteman