PHP Classes

File: example.php

Recommend this page to a friend!
  Classes of Aleksandar Zivanovic   PHP Auto Dependency Injection   example.php   Download  
File: example.php
Role: Example script
Content type: text/plain
Description: Example script
Class: PHP Auto Dependency Injection
Create objects classes and dependent classes
Author: By
Last change: better comments
Date: 8 years ago
Size: 1,865 bytes
 

Contents

Class file image Download
<?php

class ExampleA
{
    public
$variable;
}

class
ExampleB
{
    public
$exampleA;

    public
$uniqueId;

    public function
__construct(ExampleA $exampleA)
    {
       
$this->exampleA = $exampleA;

       
$this->exampleA->variable = uniqid();
    }
}

class
ExampleC
{
    public function
methodWithDependencies(ExampleA $a, ExampleB $b, $customInteger, $customString)
    {
       
var_dump($a->variable, $b->uniqueId, $customInteger, $customString);
    }
}

// Creates new instance of ExampleB and returns it
$exampleBOne = AutoDi::getInstance(ExampleB::class);

// Gets already created instance of ExampleB (Singleton)
$exampleBTwo = AutoDi::getInstance(ExampleB::class);

// Creates new instance of ExampleB without affecting previous
$exampleBThree = AutoDi::getNewInstance(ExampleB::class);

// Set value in $exampleBOne
$exampleBOne->uniqueId = 'this value SHOULD NOT be printed out!!!';

// Set value in $exampleBThree
$exampleBThree->uniqueId = 'this value is for itself';

// Set value in $exampleBTwo
$exampleBTwo->uniqueId = 'this value SHOULD be printed out!!!';

// Executes method "methodWithDependencies" from object (ExampleC)
// last argument are parameters of method that are scalar type or non typed
// e.g:
//
// methodWithDependencies(ExampleA $a, ExampleB $b, $customInteger, $customString)
// AutoDi will inject first and second parameter (ExampleA and ExampleB) and use
// values from array that is last argument of AutoDi::autoInvoke
//
// if method looked something like this
// methodWithDependencies(ExampleA $a, $customInteger, ExampleB $b, $customString)
// AutoDi will map non typed parameters with array elements, so $customInteger and $customString
// will be same as in previous example because of order
AutoDi::autoInvoke(AutoDi::getInstance(ExampleC::class), 'methodWithDependencies', [1, 'string']);