Constructor injection and its benefits

Dependencies in php are injected in mainly 2 ways.

  • Setter injection
  • Constructor injection

Example of setter injection (ideally should not be used)

public function setUserRepository(Repository $user): void
{
    $this->userRepository = $user;
}

$object = new MyClass();
$object->setUserRepository($userRepo);

The setter injection violates 2 rules.
1) It creates the MyClass object in a invalid state.
2) Services should not be able to change them once they have been created.

Constructor injection (best practice)

use SomeCompany\SomeModule\Model\UserFactory;
use SomeCompany\SomeModule\Model\User;

class InjectUsingConstructorParameters
{
    /** @var User */
    private $user;

    /**
    * @param User $user
    */
    public function __construct(
        User $user
    ) {
        $this->user = $user;
    }
}

The code above is using magento framework, but similar techniques can be applied in frameworks like symfony and laravel.

what clients say about us

Client testimonials

Our sites look great and run smoothly. Thanks for all your hard work and patience in getting us to where we are today.

contact us

Contact Us

If you have questions or want us to send you a quote for project please email us.

latest news

Articles

PHPUnit mock magic functions
Learn more about PHPUnit Partial Mock.