我想註冊我自己的類作爲服務與symfony依賴注入組件幫助,但我有類加載的問題。Symfony依賴注入和你自己的服務
我的文件結構如下:
我生成類很簡單
<?php
namespace Localhost\Service\String;
class Generator {
private $iStringLength;
public function __construct($iNewStringLength = 5) {
$this->iStringLength = $iNewStringLength;
}
public function getRandomString() {
$sChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$sRandChar = substr(str_shuffle(str_repeat($sChars,5)),0, $this->iStringLength);
return $sRandChar;
}
}
和索引都
<?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();
什麼,我得到的是一個錯誤
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
或者作爲一個圖片
這是symfony2項目嗎?或者你想只使用DependencyInjection組件? – NHG
只有DependencyInjection組件 – MyMomSaysIamSpecial