php - Symfony __construct 用法
问题描述
我对 Symfony(第 4 版)比较陌生,并试图实现__construct
依赖注入的方法。
目前,我正在通过自己的实现(在我知道该__construct
方法之前)“注入”依赖项,如下所示:
路线.yaml
fetch:
path: /fetch/{req}
controller: App\Controller\Fetch::init
requirements:
req: ".+"
/fetch 路由调用该init()
方法,该方法用作构造函数。
控制器类
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use App\Services\Utilities; // a bunch of useful functions
class Fetch extends BaseController {
private $u;
public function init(Utilities $u) {
$this->u = $u; // set the $u member with an instance of $u
}
private function do_fetch(){
$this->u->prettyprint('hello service'); // use one of $u's methods
}
}
如果你愿意的话,我在阅读文档之前想出了这个临时方案,它几乎完全详细地说明了这一点(我得到了一个 cookie)。
一个区别是文档__construct()
代替了我的init()
方法。以下是上面链接的文档页面的示例:
// src/Service/MessageGenerator.php
use Psr\Log\LoggerInterface;
class MessageGenerator
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function getHappyMessage()
{
$this->logger->info('About to find a happy message!');
// ...
}
}
但是当我交换init()
并__construct()
更新 routes.yaml 时,我得到了一个错误。
// .....
class Fetch extends BaseController {
private $u;
public function __construct(Utilities $u) {
$this->u = $u; // set the $u member with an instance of $u
}
// ....
fetch:
path: /fetch/{req}
controller: App\Controller\Fetch::__construct
requirements:
req: ".+"
它要求我提供一个参数,__construct
因为该方法需要一个 ( $u
),但在充当构造函数时并非如此。init()
此外,我觉得由于该__construct()
方法是一个内置的钩子,Symfony 应该知道使用它,而无需我在 routes.yaml 中明确告诉它。但是,排除它也会引发错误。
routes.yaml(__construct 未明确指出)
fetch:
path: /fetch/{req}
controller: App\Controller\Fetch
requirements:
req: ".+"
我在这里想念什么?
解决方案
推荐阅读
- math - 数学符号还是伪代码?
- ruby-on-rails - accept_nested_attributes_for 与 Rails 中的关系数据库逻辑相矛盾
- algorithm - 无向投影依赖解析算法
- android - 为什么我的 SwitchCompat OnCheckedChangeListener 在创建时触发,我该如何阻止它?
- c# - C# 使用 ComboBox 中的选定项
- batch-file - 混合 Batch-VBScript 文件中的发送键
- java - Java Regex 从字符串中提取数字和字符串
- react-native - ReactNative如何设置Text组件文本垂直居中
- apache-camel - 在 Apache ServiceMix Bundle 中创建路由:列表状态为宽限期
- python - 使用 Opencv 库制作视频,但不确定如何指定或将其转换为 h264 编解码器格式