The MonadThrow class might look something like this:
interface MonadThrow extends Monad {
function throwM($errObj);
}
This will make it easier to make methods generic in their return monads. For example, one could write a database-querying method like so:
class MyRepository {
function getEntityById(string $id, $monadThrow = new MaybeMonad()) {
$dbEntity = ... // query the database
return is_null($dbEntity) ?
$monadThrow->throwM("Entity with ID: " . $id . " could not be found.") :
$monadThrow->pure($dbEntity);
}
}
If the caller desires the return type to be Maybe, they could simply call it like this:
$maybeEntity = $repository->getEntityById("123456");
But if, say, an Attempt is desired, then they could call it like this:
$attemptEntity = $repository->getEntityById("123456", new AttemptMonad());
This presumes, of course, that both MaybeMonad and AttemptMonad have implemented the MonadThrow interface.
The
MonadThrowclass might look something like this:This will make it easier to make methods generic in their return monads. For example, one could write a database-querying method like so:
If the caller desires the return type to be
Maybe, they could simply call it like this:But if, say, an
Attemptis desired, then they could call it like this:This presumes, of course, that both
MaybeMonadandAttemptMonadhave implemented theMonadThrowinterface.