R
R
Roman2014-02-25 13:16:39
symfony
Roman, 2014-02-25 13:16:39

Symfony Dependency Injection and your class as a service?

I am studying namespaces and dependency injection along with a combat task and ran into a problem that when I try to register my class as a service, the symphony component does not find it. (question on stackoverflow: stackoverflow.com/questions/22010568/symfony-depen...
Project structure
SHqL1Fd.png
My Generator class

<?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.php
<?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();

But I get
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
It's clear that I didn't find a class to register, but I still can't imagine how to add it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Skobkin, 2016-02-28
@Nerfair

Did you try to specify FQCN (full class name) when registering the service:

$oContainer
    ->register('generator', 'Localhost\Service\String\Generator')
    ->addArgument('15');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question