2
\$\begingroup\$

Here is a class that executes the CreateAPerson use case. It takes a request object (which is a simple data structure), validates the request, creates a new person, and then returns a response object (another simple data structure).

For testability, I've created a setter that allows me to inject a mocked entity manager (I'm using Doctrine for persistence).

I realize this is rather simple, but do you see any red flags on the testability of this code?

<?php

namespace Stratus\UseCase\CreateAPerson;

class Interactor
{
    protected $entityManager;

    function __construct()
    {
        $doctrine = new \Stratus\Repository\Doctrine();
        $this->entityManager = $doctrine->getManager();
    }

    public function execute(Request $request)
    {
        if (!$request->isValid())
            throw new \Stratus\Exception\InvalidRequestException('Request did not pass validation.');

        $person = new \Stratus\Entity\Person();
        $person->setFirstName($request->firstName);

        $this->entityManager->persist($person);

        $response = new Response();
        $response->id = $person->getID();

        return $response;
    }

    public function setEntityManager($entityManager)
    {
        $this->entityManager = $entityManager;
    }
}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Constructor injection

Use constructor injection becouse this is the best way to write well readable and testable code. If you don't need a Doctrine instance in your class then don't use it.

public function __construct($entityManager)
    {
        $this->setEntityManager($entityManager);
    }
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.