MyMomSaysIamSpecial MyMomSaysIamSpecial - 1 year ago 128
PHP Question

Symfony dependency injection and your own services

I am trying to register my own class as a services with help of symfony dependency injection component, but i have problems with class loading.

I have file structure as this:

enter image description here

My Generator class is simple

<?php

namespace Localhost\Service\String;

class Generator {

private $iStringLength;

public function __construct($iNewStringLength = 5) {
$this->iStringLength = $iNewStringLength;
}

public function getRandomString() {
$sChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$sRandChar = substr(str_shuffle(str_repeat($sChars,5)),0, $this->iStringLength);

return $sRandChar;
}
}


And Index is

<?php

require_once 'vendor/autoload.php';

/*
spl_autoload_register(function ($sClass) {
echo $sClass;
require_once str_replace('\\', '/', $sClass) . '.php';
});
*/

use Localhost\Service\String\Generator;

/*
$oStringGenerator = new Generator(55);
echo $oStringGenerator->getRandomString();
*/

use Symfony\Component\DependencyInjection\ContainerBuilder;

$oContainer = new ContainerBuilder();
$oContainer
->register('generator', 'Generator')
->addArgument('15');

$oGeneratorService = $oContainer->get('generator');
echo $oGeneratorService->getRandomString();


What i am getting is an error

Fatal error: Uncaught exception 'ReflectionException' with message 'Class Generator does not exist' in D:\Localhost\Apache\htdocs\Test\vendor\symfony\dependency-injection\Symfony\Component\DependencyInjection\ContainerBuilder.php:959 Stack trace: #0 D:\Localhost\Apache\htdocs\Test\vendor\symfony\dependency-injection\Symfony\Component\DependencyInjection\ContainerBuilder.php(959): ReflectionClass->__construct('Generator') #1 D:\Localhost\Apache\htdocs\Test\vendor\symfony\dependency-injection\Symfony\Component\DependencyInjection\ContainerBuilder.php(493): Symfony\Component\DependencyInjection\ContainerBuilder->createService(Object(Symfony\Component\DependencyInjection\Definition), 'generator') #2 D:\Localhost\Apache\htdocs\Test\index.php(26): Symfony\Component\DependencyInjection\ContainerBuilder->get('generator') #3 {main} thrown in D:\Localhost\Apache\htdocs\Test\vendor\symfony\dependency-injection\Symfony\Component\DependencyInjection\ContainerBuilder.php on line 959


Or as a picture

enter image description here

Answer Source
$oContainer = new ContainerBuilder();
$oContainer
    ->register('generator', 'Localhost\Service\String\Generator')
    ->addArgument('15');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download