【发布时间】:2017-07-19 16:09:22
【问题描述】:
我不明白为什么我不能创建自定义服务。我在这两种技术上都遇到了错误。我在您的文档中没有找到任何关于此的内容。
# app/config/services.yml
services:
jdf.utils.phphelper:
class: JDF\Utils\PhpHelper
// src/JDF/Utils/PhpHelper.php
namespace JDF\Utils;
class PhpHelper
{
/**
* [pdebug description]
* @param string $var The string to beautiful show
* @param string $msg Description of the $var
* @param integer $displayNone
* @return echo pre print_r $var string
*/
public function pdebug ($var, $msg = '', $displayNone = 0) {
}
}
案例1:(在__construct函数中传递PhpHelper)
// src/JDF/CsvTreatmentBundle\Controller/ImportController
namespace JDF\CsvTreatmentBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use JDF\Utils\PhpHelper;
use Psr\Log\LoggerInterface;
/**
*
*/
class ImportController extends Controller {
function __construct(
PhpHelper $PhpHelper
) {
}
public function indexAction() {
//$test = $this->container->get('jdf.utils.phphelper');
return new Response('<hr>');
}
} /*End of class*/
错误 1: 可捕获的致命错误:传递给 JDF\CsvTreatmentBundle\Controller\ImportController::__construct() 的参数 1 必须是 JDF\Utils\PhpHelper 的实例,没有给出,在 C:\kitutilitaire\vendor\symfony\symfony\src\Symfony 中调用\Component\HttpKernel\Controller\ControllerResolver.php 在第 202 行并定义 500 内部服务器错误 - ContextErrorException
案例 2(只需使用 get() 控制器方法):
// src/JDF/CsvTreatmentBundle\Controller/ImportController
namespace JDF\CsvTreatmentBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use JDF\Utils\PhpHelper;
use Psr\Log\LoggerInterface;
/**
*
*/
class ImportController extends Controller {
function __construct(
//PhpHelper $PhpHelper
// LoggerInterface $logger
) {
}
public function indexAction() {
$test = $this->container->get('jdf.utils.phphelper');
// $logger = $this->container->get('logger');
return new Response('<hr>');
}
} /*End of class*/
错误 2: 尝试从命名空间“JDF\Utils”加载类“PhpHelper”。 您是否忘记了另一个命名空间的“使用”语句?
堆栈跟踪
in var\cache\dev\appDevDebugProjectContainer.php at line 3555 -
*/
protected function getJdf_Utils_PhphelperService()
{
return $this->services['jdf.utils.phphelper'] = new \JDF\Utils\PhpHelper();
}
/**
编辑:composer.json 自动加载
"autoload": {
"psr-4": {
"AppBundle\\": "src/AppBundle/",
"JDF\\CsvTreatmentBundle\\": "src/JDF/CsvTreatmentBundle/",
"JDF\\Utils\\": "src/JDF/Utils/PhpHelper"
},
"classmap": ["app/AppKernel.php", "app/AppCache.php"]
},
提前感谢您的帮助。
【问题讨论】: