PHP code example of zkrati / class-factory

1. Go to this page and download the library: Download zkrati/class-factory library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

zkrati / class-factory example snippets


// create ClassFactory
$factory = new Zkrati\ClassManagement\ClassFactory();

// add class to ClassFactory, where first argument is a class name and second argument is an array of dependencies
$factory->addClass("Example\ClassName", array("First\Dependency", "Second\One");

// get instance of the class
$factory->getInstance("Example\ClassName");

// create array like this one. Manualy in the code or parse from config file.
array(3) {
  ["Url\UrlTools"]=>
  array(1) {
    [0]=>
    string(22) "Nette\Database\Context"
  }
  ["Nette\Database\Context"]=>
  array(2) {
    [0]=>
    string(25) "Nette\Database\Connection"
    [1]=>
    string(24) "Nette\Database\Structure"
  }
  ["Nette\Database\Structure"]=>
  array(2) {
    [0]=>
    string(25) "Nette\Database\Connection"
    [1]=>
    string(34) "Nette\Caching\Storages\FileStorage"
  }
}

// give this group of classes to ClassFactory
$factory->addMultiple(array_of_classes);

$myClass = new Example\ClassName();

// add created instance to ClassFactory
$factory->addInstance($myClass);

// and than you cen get it
$factory->getInstance("Example\ClassName");

try{
    // get instance of unknown class
    $factory->getInstance("Unknown\ClassName");
} catch(UnknownClassnameException $e) {
    $e->getMessage();
}