Skip to content

Instantly share code, notes, and snippets.

@webdevilopers
Created January 12, 2018 12:05
Show Gist options
  • Save webdevilopers/321b6c1a1db50c8edd49f9b1d92b4a8b to your computer and use it in GitHub Desktop.
Save webdevilopers/321b6c1a1db50c8edd49f9b1d92b4a8b to your computer and use it in GitHub Desktop.
Command Handling Policy / Strategy Pattern in Application Services
<?php
namespace Rewotec\TimeTracking\Application\Employee;
use Rewotec\TimeTracking\Domain\Model\Employee\AssignableJobFunctionPolicy;
use Rewotec\TimeTracking\Domain\Model\Employee\Employee;
use Rewotec\TimeTracking\Domain\Model\Employee\EmployeeRepository;
/**
* Class AssignEmployeeHandler
* @package Rewotec\TimeTracking\Application\Employee
* @author Michael Borchers <m.borchers@rewotec.com>
*/
final class AssignEmployeeHandler
{
/** @var AssignableJobFunctionPolicy $jobFunctionPolicy */
private $jobFunctionPolicy;
/** @var EmployeeRepository $employees */
private $employees;
/**
* AssignEmployeeHandler constructor.
* @param AssignableJobFunctionPolicy $jobFunctionPolicy
* @param EmployeeRepository $employees
*/
public function __construct(AssignableJobFunctionPolicy $jobFunctionPolicy, EmployeeRepository $employees)
{
$this->jobFunctionPolicy = $jobFunctionPolicy;
$this->employees = $employees;
}
/**
* @param AssignEmployee $command
*/
public function __invoke(AssignEmployee $command)
{
if (!$this->jobFunctionPolicy->isSatisfiedBy($command->jobFunctionId())) {
// Employees whose job function is not linked to an activity are not assigned.
return;
}
$employee = Employee::assign(
$command->employeeId(), $command->personnelNumber(), $command->firstName(), $command->lastName(),
$command->companyId(), $command->startDate(), $command->leavingDate(),
$command->workerCategory(), $command->jobFunctionId()
);
$this->employees->add($employee);
}
}
@webdevilopers
Copy link
Author

Throwing an exception feels like something went "wrong". But actually it's not the case. The data per se was valid. The application is just not interested in storing the data at all.

I like my handlers to simply store of fail. But not to check something in between. That is "superficial" validation and feels better before the attempt to create and store.

@codeliner
Copy link

Where does the AssignEmployee command come from? And who is interested in the result?

@webdevilopers
Copy link
Author

A Process Manager / Consumer receives all employees. It then creates the AssignEmployee command.
Currently then the Command Handler gets injected a Policy that decides if the command holds the correct JobFunctionId.
If not, the Command can be ignored. Otherwise the Aggregate Employee can be created and stored inside the Repository.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment