Dependency injection in PHP traits

php trait constructor
php trait vs dependency injection
php trait implement interface

Do traits actually work with dependency injection? Consider the following code:

Trait Class

namespace Frame\Slick\Block;
use Frame\Slider\Slick\Block\Data as Helper

trait Slick
{
   protected $_slickHelper;
   public function __construct(Helper $slickHelper) 
   {
     $this->_slickHelper = $slickHelper;
   }
}

Class using the trait

namespace Frame\Slick\Block;

class Product ListProduct implements BlockInterface 
{
   use Slick;
   public function testTrait()
   {
      return $this->_slickHelper->getHelloWorld();
   }
}

This seems to always return null, am very sure everything is being included properly. Can trait really support dependency injection?

Yes they work the code from trait is "pasted" on compliation level. Consider the following code. It works as expected and echos proper value. Your problem is elsewhere.

<?php
class Dependency
{
    public function foo()
    {
        return 'test';
    }
}

trait Slick
{
   protected $dep;

   public function __construct(Dependency $dep) 
   {
       $this->dep = $dep;
   }
}

class Product 
{
   use Slick;

   public function testTrait()
   {
      return $this->dep->foo();
   }
}

echo (new Product(new Dependency()))->testTrait();

The code will echo 'test'. Working fiddle

Dependency injection in PHP traits, Yes they work the code from trait is "pasted" on compliation level. Consider the following code. It works as expected and echos proper value. A Dependency Injection Container is something that handles dependencies for your class(es) automatically. If you have worked with Laravel or Symfony, you know that their components have dependencies on on other classes. How do they manage all of those dependencies ? Yes they use some sort of Dependency Injection Container. There are quite some dependency injection containers out there for PHP that can be used for this purpose or you can also write your own. Each container might have bit of

A properly implemented framework should be able to do dependency injection on trait constructors. Typically parameters which are eligible for injection are determined using reflection. Consider the following example:

<?php 

class D {}

trait T {

    public function __construct(D $d) { }


}

class A {

use T;

}


$cls = new ReflectionClass("A");

$ctor = $cls->getConstructor();

print_r($ctor->getParameters()[0]->getClass());

Prints:

ReflectionClass Object
(
    [name] => D
)

This indicates that the framework can use reflection to determine whether or not to inject the dependency, the fact that the constructor is in the trait does not matter.

If this is not happening in magento then I suggest you move this to their suggestion thread (if any).

I would also recommend you read up on how dependency injection works in magento via their dependency injection documentation

Dependency Injection with Traits (PHP 5.4+) · GitHub, throw new \Exception("I don't have any more 'dog' for you."); } return $this->dog;. } } trait Cat {. private $cat = false;. function setCat(\Animals\Cat $cat) {. $this->cat  Object Oriented Programming PHP Programming Dependency injection is a procedure where one object supplies the dependencies of another object. Dependency Injection is a software design approach that allows avoiding hard-coding dependencies and makes it possible to change the dependencies both at runtime and compile time.

Don't use constructors!

trait SomeTrait
{

    /**
     * @var ParameterBagInterface
     */
    protected $envParams;

    /**
     * @required
     *
     * @param ParameterBagInterface $envParams
     */
    public function setFormFactory(ParameterBagInterface $envParams)
    {
        $this->envParams = $envParams;
    }
}

Injectors: Dependency Injection with Traits – JasonLotito, Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single  Injectors: Dependency Injection with Traits With the release of PHP 5.4, Traits were added to our toolbox. And, if I might be so bold, it’s one of the most exciting features I’ve seen come out of PHP in a long time. Traits is a mechanism for code reuse in single inheritance languages such as PHP.

php, I like the introduction here but I'm afraid traits will most likely be used like global functions. Most applications I've seen so far are dubious, more play than proper  This package can be used to create objects injecting dependencies using traits. It can create a new object injecting dependencies using traits that define the injectable values or pass the values explicitly to the dependency injection container. The new objects may be created as individual instances or retrieved as singleton objects.

Traits and Dependency Injection, Normally (In L5 that is) the dependency injection of methods that are called by the <?php namespace App\lib\myutils\apputils\cmdinput; use  Dependency Injection with Traits (PHP 5.4+). GitHub Gist: instantly share code, notes, and snippets.

Traits - Manual, The precedence order is that methods from the current class override Trait methods, I'm not sure how I'll approach a more complicated parent trait constructor. Dependency injection About this guide. Read this guide if. you want to take advantage of dependency injections which can help you decoupling your code, getting more reusable code, and testing your code more easily. you want to configure Matomo differently by changing which classes it uses.

Comments
  • Which framework are you using? It really depends how dependency injection is implemented in it.
  • I am using magento 2
  • Which is a platform on top of zend framework 3
  • But you're not doing dependency injection at all
  • I've edited it with object it does the same but with objects. BTW string variable is also dependency.
  • @VentzyKunev just add as and then overload constructor and invoke aliased method and it'll work as well